hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
14ba5b2a16437d48d33cd427ba902f202cf138fa | 517 | //
// ViewController.swift
// CodeGenerationExample
//
// Created by Wolfgang Lutz on 05.05.16.
// Copyright © 2016 swinject. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.884615 | 80 | 0.676983 |
76e372f16243292bd49b8651e51a1fede0aa86f7 | 452 | // Copyright © 2021 Brad Howes. All rights reserved.
import CoreMIDI
/**
Protocol for an object that monitors MIDI input activity
*/
public protocol MIDIMonitor: AnyObject {
/**
Notification invoked when there is an incoming MIDI message.
- parameter uniqueId: the unique ID of the MIDI endpoint that sent the message
- parameter channel: the channel found in the MIDI message
*/
func seen(uniqueId: MIDIUniqueID, channel: Int)
}
| 25.111111 | 81 | 0.738938 |
e6631d2e682efbab2d08d990de9a232ff407ab6e | 3,990 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: sifnode/tokenregistry/v1/query.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct Sifnode_Tokenregistry_V1_QueryEntriesResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var registry: Sifnode_Tokenregistry_V1_Registry {
get {return _registry ?? Sifnode_Tokenregistry_V1_Registry()}
set {_registry = newValue}
}
/// Returns true if `registry` has been explicitly set.
var hasRegistry: Bool {return self._registry != nil}
/// Clears the value of `registry`. Subsequent reads from it will return its default value.
mutating func clearRegistry() {self._registry = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _registry: Sifnode_Tokenregistry_V1_Registry? = nil
}
struct Sifnode_Tokenregistry_V1_QueryEntriesRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "sifnode.tokenregistry.v1"
extension Sifnode_Tokenregistry_V1_QueryEntriesResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".QueryEntriesResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "registry"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._registry)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._registry {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Tokenregistry_V1_QueryEntriesResponse, rhs: Sifnode_Tokenregistry_V1_QueryEntriesResponse) -> Bool {
if lhs._registry != rhs._registry {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Sifnode_Tokenregistry_V1_QueryEntriesRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".QueryEntriesRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Tokenregistry_V1_QueryEntriesRequest, rhs: Sifnode_Tokenregistry_V1_QueryEntriesRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 38.365385 | 157 | 0.765414 |
8a685f20f8f7583601f417fb8dcdf52e7b33583b | 2,501 | //
// ShowNetImageViewController.swift
// topsiOSPro_Example
//
// Created by topscommmac01_lixiaojin on 2019/7/5.
// Copyright © 2019 李效晋. All rights reserved.
//
import UIKit
import topsiOSPro
import SnapKit
import AlamofireImage
import ImageSlideshow
class ShowNetImageViewController: BaseUIViewViewController {
let imageSlideShow = ImageSlideshow()
override func viewDidLoad() {
super.viewDidLoad()
var imageArr:[AlamofireSource] = []
// imageArr.append(AlamofireSource(urlString: "http://img4.imgtn.bdimg.com/it/u=688059555,2062039633&fm=26&gp=0.jpg")!)
imageArr.append(AlamofireSource(urlString: "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3253325827,761778924&fm=26&gp=0.jpg")!)
imageArr.append(AlamofireSource(urlString: "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3253325827,761778924&fm=26&gp=0.jpg")!)
// imageArr.append(AlamofireSource(urlString: "http://sjbz.fd.zol-img.com.cn/t_s720x1280c/g2/M00/0A/07/ChMlWl0essqIU5PrAA-77dSn6ZoAALjfwEg5TQAD7wF815.jpg")!)
// imageArr.append(AlamofireSource(urlString: "http://sjbz.fd.zol-img.com.cn/t_s750x1334c/g2/M00/0A/07/ChMlWl0essyIMC1PAAbZyx9kTH0AALjfwGxIsUABtnj204.jpg")!)
// imageArr.append(AlamofireSource(urlString: "http://b.zol-img.com.cn/sjbizhi/images/9/750x1334/1562292824836.jpg")!)
imageSlideShow.circular = false
imageSlideShow.contentScaleMode = .scaleAspectFill
imageSlideShow.slideshowInterval = 0;
imageSlideShow.setImageInputs(imageArr)
// imageSlideShow.circular = false
let labelPageIndicator = LabelPageIndicator()
imageSlideShow.pageIndicator = labelPageIndicator
labelPageIndicator.textColor = UIColor.white
labelPageIndicator.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
self.baseView.addSubview(imageSlideShow)
imageSlideShow.snp.makeConstraints { (make) in
make.width.height.equalTo(200)
make.center.equalTo(self.baseView.snp.center)
}
makeTapGesture()
}
func makeTapGesture() {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTap))
imageSlideShow.circular = false
imageSlideShow.addGestureRecognizer(gestureRecognizer)
}
@objc func didTap() {
imageSlideShow.presentFullScreenController(from: self)
}
}
| 36.779412 | 164 | 0.704918 |
c151658db20c78edb5c3278fd68a4a7608deddbe | 1,886 | //
// AttractorGroupsCalculator+CPU.swift
// MF Metal Example
//
// Created by Tristan Leblanc on 13/12/2020.
//
import MoofFoundation
class AttractorsGroupsCalculator: WorldCalculator {
init(world: WorldBuffers) throws {
try super.init(world: world, functionName: "computeAttractorsGroupsLocations")
}
/// Encode command
///
/// Render pass descriptor is used for more complex cases ( With vertexes ).
/// In this example, we don't need it. We simply compute pixels color, and move onscreen at the end
override func encodeCommand(commandBuffer: MTLCommandBuffer, rpd: MTLRenderPassDescriptor? = nil) throws {
let nGroups = world.numberOfAttractorsGroups
guard nGroups > 0 else {
throw Errors.attractorsGroupsBufferEmpty
}
// Start a compute pass.
guard let computeEncoder = commandBuffer.makeComputeCommandEncoder() else {
throw MetalCalculator.Errors.cantMakeCommandEncoder
}
computeEncoder.setComputePipelineState(computeFunctionPipelineState)
// Set the subdivision size - we use one thread, because we need to compute all attractors
// in sequential order.
let threadsPerThreadgroupSize = MTLSize(width: 1, height: 1, depth: 1)
// We compute thread group size.
let threadGroupsSize = MTLSize(width: 1, height: 1, depth: 1)
// Pass buffers to GPU
computeEncoder.setBuffer(world.groupsBuffer, offset: 0, index: 0)
computeEncoder.setBuffer(world.settingsBuffer, offset: 0, index: 1)
// Dispatch threads
computeEncoder.dispatchThreadgroups(threadGroupsSize, threadsPerThreadgroup: threadsPerThreadgroupSize)
// Send commands to GPU
computeEncoder.endEncoding()
}
}
| 35.584906 | 111 | 0.661188 |
48d044fd1de7cd4802ed0b46afa369ce8ab0fc4c | 10,035 | //
// JNAvatarWithInitials.swift
// JNAvatarWithInitials
//
// Created by JN Disrupter on 9/13/17.
// Copyright © 2017 JN Disrupter. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
/// Image completion block
public typealias ImageCompletionBlock = (UIImage?, Error? , URL?) -> Void
/// Avatar with initilas on it if needed
open class JNAvatarWithInitials: UIView {
/// Initials label
@IBOutlet private weak var initialsLabel: UILabel!
/// Avatar image
@IBOutlet private weak var avatarImage: UIImageView!
/// Intial Label Top Constraint
@IBOutlet private weak var initialLabelTopConstraint: NSLayoutConstraint!
/// Intial Label Bottom Constraint
@IBOutlet private weak var initialLabelBottomConstraint: NSLayoutConstraint!
/// Initials font
open var initialsFont = UIFont.systemFont(ofSize: 14) {
didSet {
// Set font
self.initialsLabel.font = self.initialsFont
// Call display
self.setNeedsDisplay()
}
}
/// Initials text color
open var initialTextColor = UIColor.black {
didSet {
// Set text color
self.initialsLabel.textColor = initialTextColor
// Call display
self.setNeedsDisplay()
}
}
/// Initials label insets
open var initialLabelInset = UIEdgeInsets.zero {
didSet {
// Set Top Constraint
self.initialLabelTopConstraint.constant = initialLabelInset.top
// Set Bottom Constraint
self.initialLabelBottomConstraint.constant = initialLabelInset.bottom
// Call display
self.layoutIfNeeded()
}
}
/// Avatar content mode
open var avatarContentMode : UIView.ContentMode = UIView.ContentMode.scaleAspectFill {
didSet {
// Set image content mode
self.avatarImage.contentMode = self.avatarContentMode
// Call display
self.setNeedsDisplay()
}
}
/**
Loads a view instance from the xib file
- returns: loaded view
*/
private func loadViewFromXibFile() -> UIView {
let bundle = Bundle(for: JNAvatarWithInitials.self)
let nib = UINib(nibName: "JNAvatarWithInitials", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.autoresizingMask = [.flexibleHeight,.flexibleWidth]
return view
}
/**
Default initializer
*/
convenience init() {
self.init(frame: CGRect())
}
/**
Initialiser method with frame
*/
public override init(frame: CGRect) {
super.init(frame: frame)
// Setup view
self.setupView()
}
/**
Initialiser method with NSCoder
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Setup view
self.setupView()
}
/**
Sets up the view by loading it from the xib file and setting its frame
*/
private func setupView() {
let view = loadViewFromXibFile()
view.frame = bounds
self.addSubview(view)
// Add constarins to view
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
// Setup view
self.clipsToBounds = true
self.initialsLabel.textAlignment = .center
// Reset view
self.resetView()
}
/**
Layout subviews
*/
override open func layoutSubviews() {
super.layoutSubviews()
// Get Min Value between Width and Height and update font to fit view
let fontSize = min(self.frame.size.height , self.frame.size.width) / 3
self.initialsLabel.font = initialsFont.withSize(fontSize)
}
/**
Setup view
- parameter imageUrl: The image url to load
- parameter placeHolderImage: Place holder image
- parameter fullName: Full name which will be used to set initials
- parameter showInitails: boolean to indicate if the initials should appear
*/
open func setup(imageUrl : String , placeHolderImage : UIImage! = nil , fullName : String , showInitails : Bool = false , completion : ImageCompletionBlock? = nil) {
// Reset view
self.resetView()
// Set iamge view content mode
self.avatarImage.contentMode = self.avatarContentMode
// hide name label
self.initialsLabel.isHidden = true
// Check if image url is empty
if !imageUrl.isEmpty {
// Setup avatar image
self.avatarImage.sd_imageIndicator = SDWebImageActivityIndicator.gray
self.avatarImage.sd_setImage(with: URL(string:imageUrl), placeholderImage: placeHolderImage, options: SDWebImageOptions.continueInBackground, completed: { [ weak self] (image, error, cacheType, imageURL) in
guard let strongSelf = self else {return}
if error != nil {
if showInitails {
// Show initialis
strongSelf.showInitials(fullName: fullName)
} else {
// Set placeholder image
strongSelf.avatarImage.image = placeHolderImage
}
}
// Call completion
if let completion = completion {
completion(strongSelf.avatarImage.image,error,imageURL)
}
})
} else if showInitails {
// Show initialis
self.showInitials(fullName: fullName)
// Call completion
if let completion = completion {
completion(nil,nil,nil)
}
} else {
// Set placeholder image
self.avatarImage.image = placeHolderImage
// Call completion
if let completion = completion {
completion(placeHolderImage,nil,nil)
}
}
}
/**
Setup view
- parameter image: The uiimage to load
- parameter placeHolderImage: Place holder image
- parameter fullName: Full name which will be used to set initials
- parameter showInitails: boolean to indicate if the initials should appear
*/
open func setup(image : UIImage? , placeHolderImage : UIImage! = nil , fullName : String , showInitails : Bool = false , completion : ImageCompletionBlock? = nil) {
// Reset view
self.resetView()
// Set iamge view content mode
self.avatarImage.contentMode = self.avatarContentMode
// hide name label
self.initialsLabel.isHidden = true
// Get image from image name
if let image = image {
// Set image
self.avatarImage.image = image
} else if showInitails {
// Show initialis
self.showInitials(fullName: fullName)
} else {
// Set placeholder image
self.avatarImage.image = placeHolderImage
}
// Call completion
if let completion = completion {
completion(self.avatarImage.image,nil,nil)
}
}
/**
Reset view
*/
private func resetView() {
// Reset image
self.avatarImage.image = nil
// Reset intialis label
self.initialsLabel.isHidden = true
self.initialsLabel.text = ""
// Cancel sd webimage download
self.avatarImage.sd_cancelCurrentImageLoad()
self.avatarImage.sd_imageIndicator = nil
}
/**
Show Initials
- parameter fullName: The full name
*/
private func showInitials(fullName : String) {
// Reset image
self.avatarImage.image = nil
// Trim full name and separat it by space
let displayNameArray = fullName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).components(separatedBy: " ")
// Build initails text
var initialsString = ""
if !displayNameArray.isEmpty {
if displayNameArray.count == 1 && displayNameArray[0].count > 1 {
let index = displayNameArray[0].index(displayNameArray[0].startIndex, offsetBy: 2)
initialsString = String(displayNameArray[0][..<index])
}
// Check if there is first and last name
else if displayNameArray.count > 1 {
if let firstCharacter = displayNameArray.first?.first , let secondCharachter = displayNameArray.last?.first {
initialsString = String(describing: firstCharacter) + String(describing: secondCharachter)
}
}
}
// Set initials text
self.initialsLabel.text = initialsString.uppercased()
// Show initials Label
self.initialsLabel.isHidden = false
}
/**
Get image view
- Returns: avatar image view
*/
open func getImageView() -> UIImageView {
return self.avatarImage
}
}
| 31.261682 | 219 | 0.569208 |
1eeb6aa57dbfdf009394e93a9a0e8e7cb54461de | 1,223 | //
// BiBaoController.swift
// SwiftCW
//
// Created by YiXue on 17/3/22.
// Copyright © 2017年 赵刘磊. All rights reserved.
//
import UIKit
//MARK: 全局练习
typealias globalBlock1 = () -> Void
typealias globalBlock2 = () -> ()
typealias globalBlock3 = (String) -> Void
typealias globalBlock4 = () -> String
typealias globalBlock5 = (String) -> String
class BiBaoController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
//MARK: 常量练习
var constBlock1 = {
() -> Void in
}
var constBlock2 = {
}
var constBlock3 = {
(a:String) -> Void in
}
var constBlock4 = {
(a:String) -> String in
return ""
}
//Mark:函数参数练习
func funcBlock1(a:() -> ()){
}
func funcBlock2(a:(String) -> ()){
}
func funcBlock3(a:(String) -> (String)){
}
//MARK:逃逸闭包
func funcBlock4(a:@escaping () -> ()){
DispatchQueue.main.asyncAfter(deadline: .now()) {
a()
}
return
}
}
}
| 19.109375 | 62 | 0.464432 |
8aa742542d7a277257c8e4b1c93e965b62a2806d | 1,000 | /**
* Copyright (c) 2021 Dustin Collins (Strega's Gate)
* All Rights Reserved.
* Licensed under Apache License v2.0
*
* Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate
*/
import WinSDK
@available(Windows, introduced: 10.0.17763)
public class LifetimeTracker: DeviceChild {
override class var interfaceID: WinSDK.IID {RawValue.interfaceID}
}
@available(Windows, introduced: 10.0.17763)
extension LifetimeTracker {
typealias RawValue = WinSDK.ID3D12LifetimeTracker
convenience init(_ rawValue: inout RawValue) {
self.init(win32Pointer: &rawValue)
}
}
@available(Windows, introduced: 10.0.17763)
extension LifetimeTracker.RawValue {
static var interfaceID: IID {WinSDK.IID_ID3D12LifetimeTracker}
}
//MARK: - Original Style API
#if !Direct3D12ExcludeOriginalStyleAPI
@available(Windows, introduced: 10.0.17763)
@available(*, deprecated, renamed: "LifetimeTracker")
public typealias ID3D12LifetimeTracker = LifetimeTracker
#endif | 27.777778 | 79 | 0.756 |
7ad022f31e62bb8ac391290f0011177d779e7451 | 4,278 | //
// AgentTests.swift
// SwiftAgentTests
//
// Created by Joshua Smith on 3/19/15.
// Copyright (c) 2015 iJoshSmith. All rights reserved.
//
import XCTest
class SwiftAgentTests: XCTestCase
{
// MARK: - get
func test_get_valueIsHello_returnsHello()
{
let agent = Agent { "Hello" }
XCTAssertEqual(agent.get(), "Hello", "")
}
func test_get_valueIs1Plus1_returns2()
{
let agent = Agent { 1 + 1 }
XCTAssertEqual(agent.get(), 2, "")
}
func test_get_passValueTransformer_returnsTransformedValue()
{
let agent = Agent { 42 }
let value = agent.get { "agent value is \($0)" }
XCTAssertEqual(value, "agent value is 42", "")
}
// MARK: - mutate
func test_mutate_addDictionaryEntry_entryIsAdded()
{
let agent = Agent { NSMutableDictionary(dictionary: ["A": 1]) }
agent.mutate { $0["B"] = 2 }
XCTAssertEqual(agent.get()["A"] as? Int, 1, "")
XCTAssertEqual(agent.get()["B"] as? Int, 2, "")
}
func test_mutate_addBToSetThenRemoveA_onlyContainsB()
{
let agent = Agent { NSMutableSet(object: "A") }
agent.mutate { $0.addObject("B") }
agent.mutate { $0.removeObject("A") }
XCTAssertEqual(agent.get().count, 1, "")
XCTAssertTrue(agent.get().containsObject("B"), "")
}
// MARK: - update
func test_update_increment100_valueIs101()
{
let agent = Agent { 100 }
agent.update { $0 + 1 }
XCTAssertEqual(agent.get(), 101, "")
}
// MARK: - updateAndGet
func test_updateAndGet_increment100_valueIs101()
{
let agent = Agent { 100 }
let value = agent.updateAndGet { $0 + 1 }
XCTAssertEqual(value, 101, "")
XCTAssertEqual(agent.get(), 101, "")
}
func test_updateAndGet_ignoreCurrentValue_valueIsReplaced()
{
let agent = Agent { "Happy Happy" }
let value = agent.updateAndGet { _ in "Joy"}
XCTAssertEqual(value, "Joy", "")
XCTAssertEqual(agent.get(), value, "")
}
// MARK: - concurrency test
func test_update_4ThreadsIncrement250Times_valueIs1000()
{
let agent = Agent { 0 }
// Each quality-of-service class represents a separate
// dispatch queue running on a different thread.
[QOS_CLASS_DEFAULT,
QOS_CLASS_BACKGROUND,
QOS_CLASS_USER_INITIATED,
QOS_CLASS_USER_INTERACTIVE]
.map { qosClass in
AgentUpdater(
agent: agent,
block: { $0 + 1 },
count: 250,
delay: 0.001,
queue: dispatch_get_global_queue(qosClass, 0))
}
.each { $0.startUpdating() }
// Pause the current thread while the Agent is updated.
NSThread.sleepForTimeInterval(2)
XCTAssertEqual(agent.get(), 1000, "")
}
}
class AgentUpdater<T>
{
let agent: Agent<T>
let block: (T) -> T
let count: Int
let delay: NSTimeInterval
let queue: dispatch_queue_t
init(
agent: Agent<T>,
block: (T) -> T,
count: Int,
delay: NSTimeInterval,
queue: dispatch_queue_t)
{
self.agent = agent
self.block = block
self.count = count
self.delay = delay
self.queue = queue
}
func startUpdating()
{
dispatch_async(queue) { self.doUpdates() }
}
private func doUpdates()
{
[Int](1...self.count).each { self.doUpdate($0) }
}
private func doUpdate(updateNumber: Int)
{
let duration = delay * NSTimeInterval(updateNumber)
wait(duration, then: { self.agent.update(self.block) } )
}
private func wait(duration: NSTimeInterval, then: () -> Void)
{
let diff = Int64(duration * NSTimeInterval(NSEC_PER_SEC))
let time = dispatch_time(DISPATCH_TIME_NOW, diff)
dispatch_after(time, queue, then)
}
}
extension Array
{
func each(closure: (Element) -> Void)
{
for elem in self { closure(elem) }
}
func each(closure: () -> Void)
{
for _ in self { closure() }
}
}
| 25.616766 | 71 | 0.560542 |
e5444df3d56d9b1978550dd4fccae3f6737df929 | 1,732 | //
// AmityPhotoViewerControllerDelegate.swift
// AmityUIKit
//
// Created by Nontapat Siengsanor on 26/7/2563 BE.
// Copyright © 2563 Amity Communication. All rights reserved.
//
import UIKit
@objc public protocol AmityPhotoViewerControllerDelegate: NSObjectProtocol {
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, didScrollToPhotoAt index: Int)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, didZoomOnPhotoAtIndex: Int, atScale scale: CGFloat)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, didEndZoomingOnPhotoAtIndex: Int, atScale scale: CGFloat)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, willZoomOnPhotoAtIndex: Int)
@objc optional func photoViewerControllerDidReceiveTapGesture(_ photoViewerController: AmityPhotoViewerController)
@objc optional func photoViewerControllerDidReceiveDoubleTapGesture(_ photoViewerController: AmityPhotoViewerController)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, willBeginPanGestureRecognizer gestureRecognizer: UIPanGestureRecognizer)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, didEndPanGestureRecognizer gestureRecognizer: UIPanGestureRecognizer)
@objc optional func photoViewerControllerDidEndPresentingAnimation(_ photoViewerController: AmityPhotoViewerController)
@objc optional func photoViewerController(_ photoViewerController: AmityPhotoViewerController, scrollViewDidScroll: UIScrollView)
}
| 54.125 | 171 | 0.832564 |
e428dd7fcf0bb35f58da4a51322f842ae5e686b0 | 853 | //
// Strinng+Extensions.swift
// SwiftyAPNS
//
// Created by Sergii Tkachenko on 18.08.2020.
// Copyright © 2020 Sergii Tkachenko. All rights reserved.
//
import Foundation
public typealias P8 = String
internal enum P8Error: LocalizedError {
case invalidP8
public var errorDescription: String? {
switch self {
case .invalidP8:
return "The .p8 string has invalid format."
}
}
}
internal extension P8 {
/// Convert PEM format .p8 file to DER-encoded ASN.1 data
func toASN1() throws -> ASN1 {
let base64 = self
.split(separator: "\n")
.filter({ $0.hasPrefix("-----") == false })
.joined(separator: "")
guard let asn1 = Data(base64Encoded: base64) else {
throw P8Error.invalidP8
}
return asn1
}
}
| 21.871795 | 61 | 0.583822 |
bbf16cb4d18cb4a6788ca265897bd3fdf107b92d | 494 | //
// VirtualCommand.swift
// virtual
//
// Created by Kenneth Endfinger on 7/28/20.
//
import ArgumentParser
import Foundation
import Virtualization
struct VirtualCommand: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "virtual",
abstract: "Linux Virtual Machines for macOS",
subcommands: [
VirtualCommandRun.self
],
defaultSubcommand: VirtualCommandRun.self
)
@OptionGroup()
var versionOptions: VirtualVersionOptions
}
| 19.76 | 50 | 0.736842 |
16d22cae1bb956607128c4728f3cd1b517856b8b | 23,266 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Combine
import Foundation
import AWSPluginsCore
typealias StorageEngineBehaviorFactory =
(Bool,
DataStoreConfiguration,
String,
String,
String,
UserDefaults) throws -> StorageEngineBehavior
// swiftlint:disable type_body_length
final class StorageEngine: StorageEngineBehavior {
// TODO: Make this private once we get a mutation flow that passes the type of mutation as needed
let storageAdapter: StorageEngineAdapter
private let dataStoreConfiguration: DataStoreConfiguration
var syncEngine: RemoteSyncEngineBehavior?
let validAPIPluginKey: String
let validAuthPluginKey: String
var signInListener: UnsubscribeToken?
var iSyncEngineSink: Any?
@available(iOS 13.0, *)
var syncEngineSink: AnyCancellable? {
get {
if let iSyncEngineSink = iSyncEngineSink as? AnyCancellable {
return iSyncEngineSink
}
return nil
}
set {
iSyncEngineSink = newValue
}
}
var iStorageEnginePublisher: Any?
@available(iOS 13.0, *)
var storageEnginePublisher: PassthroughSubject<StorageEngineEvent, DataStoreError> {
get {
if iStorageEnginePublisher == nil {
iStorageEnginePublisher = PassthroughSubject<StorageEngineEvent, DataStoreError>()
}
// swiftlint:disable:next force_cast
return iStorageEnginePublisher as! PassthroughSubject<StorageEngineEvent, DataStoreError>
}
set {
iStorageEnginePublisher = newValue
}
}
@available(iOS 13.0, *)
var publisher: AnyPublisher<StorageEngineEvent, DataStoreError> {
return storageEnginePublisher.eraseToAnyPublisher()
}
static var systemModelSchemas: [ModelSchema] {
return [
ModelSyncMetadata.schema,
MutationEvent.schema,
MutationSyncMetadata.schema
]
}
// Internal initializer used for testing, to allow lazy initialization of the SyncEngine. Note that the provided
// storageAdapter must have already been set up with system models
init(storageAdapter: StorageEngineAdapter,
dataStoreConfiguration: DataStoreConfiguration,
syncEngine: RemoteSyncEngineBehavior?,
validAPIPluginKey: String,
validAuthPluginKey: String) {
self.storageAdapter = storageAdapter
self.dataStoreConfiguration = dataStoreConfiguration
self.syncEngine = syncEngine
self.validAPIPluginKey = validAPIPluginKey
self.validAuthPluginKey = validAuthPluginKey
}
convenience init(isSyncEnabled: Bool,
dataStoreConfiguration: DataStoreConfiguration,
validAPIPluginKey: String = "awsAPIPlugin",
validAuthPluginKey: String = "awsCognitoAuthPlugin",
modelRegistryVersion: String,
userDefault: UserDefaults = UserDefaults.standard) throws {
let key = kCFBundleNameKey as String
let databaseName = Bundle.main.object(forInfoDictionaryKey: key) as? String ?? "app"
let storageAdapter = try SQLiteStorageEngineAdapter(version: modelRegistryVersion, databaseName: databaseName)
try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas)
if #available(iOS 13.0, *) {
let syncEngine = isSyncEnabled ? try? RemoteSyncEngine(storageAdapter: storageAdapter,
dataStoreConfiguration: dataStoreConfiguration) : nil
self.init(storageAdapter: storageAdapter,
dataStoreConfiguration: dataStoreConfiguration,
syncEngine: syncEngine,
validAPIPluginKey: validAPIPluginKey,
validAuthPluginKey: validAuthPluginKey)
self.storageEnginePublisher = PassthroughSubject<StorageEngineEvent, DataStoreError>()
syncEngineSink = syncEngine?.publisher.sink(receiveCompletion: onReceiveCompletion(receiveCompletion:),
receiveValue: onReceive(receiveValue:))
} else {
self.init(storageAdapter: storageAdapter,
dataStoreConfiguration: dataStoreConfiguration,
syncEngine: nil,
validAPIPluginKey: validAPIPluginKey,
validAuthPluginKey: validAuthPluginKey)
}
}
@available(iOS 13.0, *)
private func onReceiveCompletion(receiveCompletion: Subscribers.Completion<DataStoreError>) {
switch receiveCompletion {
case .failure(let dataStoreError):
storageEnginePublisher.send(completion: .failure(dataStoreError))
case .finished:
storageEnginePublisher.send(completion: .finished)
}
}
@available(iOS 13.0, *)
private func onReceive(receiveValue: RemoteSyncEngineEvent) {
if case .mutationEvent(let mutationEvent) = receiveValue {
self.storageEnginePublisher.send(.mutationEvent(mutationEvent))
}
}
func setUp(modelSchemas: [ModelSchema]) throws {
try storageAdapter.setUp(modelSchemas: modelSchemas)
}
public func save<M: Model>(_ model: M,
modelSchema: ModelSchema,
condition: QueryPredicate? = nil,
completion: @escaping DataStoreCallback<M>) {
// TODO: Refactor this into a proper request/result where the result includes metadata like the derived
// mutation type
let modelExists: Bool
do {
modelExists = try storageAdapter.exists(modelSchema, withId: model.id, predicate: nil)
} catch {
let dataStoreError = DataStoreError.invalidOperation(causedBy: error)
completion(.failure(dataStoreError))
return
}
let mutationType = modelExists ? MutationEvent.MutationType.update : .create
if mutationType == .create && condition != nil {
let dataStoreError = DataStoreError.invalidCondition(
"Cannot apply a condition on model which does not exist.",
"Save the model instance without a condition first.")
completion(.failure(causedBy: dataStoreError))
}
let wrappedCompletion: DataStoreCallback<M> = { result in
guard modelSchema.isSyncable, let syncEngine = self.syncEngine else {
completion(result)
return
}
guard case .success(let savedModel) = result else {
completion(result)
return
}
if #available(iOS 13.0, *) {
self.log.verbose("\(#function) syncing mutation for \(savedModel)")
self.syncMutation(of: savedModel,
modelSchema: modelSchema,
mutationType: mutationType,
predicate: condition,
syncEngine: syncEngine,
completion: completion)
} else {
completion(result)
}
}
storageAdapter.save(model,
modelSchema: modelSchema,
condition: condition,
completion: wrappedCompletion)
}
func save<M: Model>(_ model: M, condition: QueryPredicate? = nil, completion: @escaping DataStoreCallback<M>) {
save(model, modelSchema: model.schema, condition: condition, completion: completion)
}
func delete<M: Model>(_ modelType: M.Type,
modelSchema: ModelSchema,
withId id: Model.Identifier,
completion: @escaping (DataStoreResult<M?>) -> Void) {
let transactionResult = queryAndDeleteTransaction(modelType, modelSchema: modelSchema, predicate: field("id").eq(id))
let deletedModel: M
switch transactionResult {
case .success(let queriedModels):
guard queriedModels.count <= 1 else {
completion(.failure(.unknown("delete with id returned more than one result", "", nil)))
return
}
guard let first = queriedModels.first else {
completion(.success(nil))
return
}
deletedModel = first
case .failure(let error):
completion(.failure(error))
return
}
guard modelSchema.isSyncable, let syncEngine = self.syncEngine else {
if !modelSchema.isSystem {
log.error("Unable to sync modelType (\(modelType)) where isSyncable is false")
}
if self.syncEngine == nil {
log.error("Unable to sync because syncEngine is nil")
}
completion(.success(deletedModel))
return
}
if #available(iOS 13.0, *) {
let syncCompletionWrapper: DataStoreCallback<Void> = { syncResult in
switch syncResult {
case .success:
completion(.success(deletedModel))
case .failure(let error):
completion(.failure(error))
}
}
self.syncDeletion(with: deletedModel,
modelSchema: modelSchema,
syncEngine: syncEngine,
completion: syncCompletionWrapper)
} else {
completion(.success(deletedModel))
}
}
func delete<M: Model>(_ modelType: M.Type,
modelSchema: ModelSchema,
predicate: QueryPredicate,
completion: @escaping DataStoreCallback<[M]>) {
let transactionResult = queryAndDeleteTransaction(modelType, modelSchema: modelSchema, predicate: predicate)
guard modelSchema.isSyncable, let syncEngine = self.syncEngine else {
if !modelSchema.isSystem {
log.error("Unable to sync model (\(modelSchema.name)) where isSyncable is false")
}
if self.syncEngine == nil {
log.error("Unable to sync because syncEngine is nil")
}
completion(transactionResult)
return
}
guard case .success(let queriedModels) = transactionResult else {
completion(transactionResult)
return
}
if #available(iOS 13.0, *) {
let syncCompletionWrapper: DataStoreCallback<Void> = { syncResult in
switch syncResult {
case .success:
completion(transactionResult)
case .failure(let error):
completion(.failure(error))
}
}
if queriedModels.isEmpty {
completion(transactionResult)
} else {
self.syncDeletions(of: modelType,
modelSchema: modelSchema,
withModels: queriedModels,
predicate: predicate,
syncEngine: syncEngine,
completion: syncCompletionWrapper)
}
} else {
completion(transactionResult)
}
}
private func queryAndDeleteTransaction<M: Model>(_ modelType: M.Type,
modelSchema: ModelSchema,
predicate: QueryPredicate) -> DataStoreResult<[M]> {
var queriedResult: DataStoreResult<[M]>?
var deletedResult: DataStoreResult<[M]>?
let queryCompletionBlock: DataStoreCallback<[M]> = { queryResult in
queriedResult = queryResult
if case .success = queryResult {
let deleteCompletionWrapper: DataStoreCallback<[M]> = { deleteResult in
deletedResult = deleteResult
}
self.storageAdapter.delete(modelType,
modelSchema: modelSchema,
predicate: predicate,
completion: deleteCompletionWrapper)
}
}
do {
try storageAdapter.transaction {
storageAdapter.query(modelType,
modelSchema: modelSchema,
predicate: predicate,
sort: nil,
paginationInput: nil,
completion: queryCompletionBlock)
}
} catch {
return .failure(causedBy: error)
}
return collapseResults(queryResult: queriedResult, deleteResult: deletedResult)
}
private func collapseResults<M: Model>(queryResult: DataStoreResult<[M]>?,
deleteResult: DataStoreResult<[M]>?) -> DataStoreResult<[M]> {
if let queryResult = queryResult {
switch queryResult {
case .success(let models):
if let deleteResult = deleteResult {
switch deleteResult {
case .success:
return .success(models)
case .failure(let error):
return .failure(error)
}
} else {
return .failure(.unknown("deleteResult not set during transaction", "coding error", nil))
}
case .failure(let error):
return .failure(error)
}
} else {
return .failure(.unknown("queryResult not set during transaction", "coding error", nil))
}
}
func query<M: Model>(_ modelType: M.Type,
modelSchema: ModelSchema,
predicate: QueryPredicate?,
sort: [QuerySortDescriptor]?,
paginationInput: QueryPaginationInput?,
completion: (DataStoreResult<[M]>) -> Void) {
return storageAdapter.query(modelType,
modelSchema: modelSchema,
predicate: predicate,
sort: sort,
paginationInput: paginationInput,
completion: completion)
}
func query<M: Model>(_ modelType: M.Type,
predicate: QueryPredicate? = nil,
sort: [QuerySortDescriptor]? = nil,
paginationInput: QueryPaginationInput? = nil,
completion: DataStoreCallback<[M]>) {
query(modelType,
modelSchema: modelType.schema,
predicate: predicate,
sort: sort,
paginationInput: paginationInput,
completion: completion)
}
func clear(completion: @escaping DataStoreCallback<Void>) {
if let syncEngine = syncEngine {
syncEngine.stop(completion: { _ in
self.storageAdapter.clear(completion: completion)
})
} else {
storageAdapter.clear(completion: completion)
}
}
func stopSync(completion: @escaping DataStoreCallback<Void>) {
if let syncEngine = syncEngine {
syncEngine.stop { _ in
completion(.successfulVoid)
}
} else {
completion(.successfulVoid)
}
}
func reset(onComplete: () -> Void) {
// TOOD: Perform cleanup on StorageAdapter, including releasing its `Connection` if needed
let group = DispatchGroup()
if #available(iOS 13.0, *) {
if let resettable = syncEngine as? Resettable {
group.enter()
DispatchQueue.global().async {
resettable.reset {
group.leave()
}
}
}
}
group.wait()
onComplete()
}
@available(iOS 13.0, *)
private func syncDeletion<M: Model>(with model: M,
modelSchema: ModelSchema,
syncEngine: RemoteSyncEngineBehavior,
completion: @escaping DataStoreCallback<Void>) {
let mutationEvent: MutationEvent
do {
mutationEvent = try MutationEvent(model: model,
modelSchema: modelSchema,
mutationType: .delete)
} catch {
let dataStoreError = DataStoreError(error: error)
completion(.failure(dataStoreError))
return
}
let mutationEventCallback: DataStoreCallback<MutationEvent> = { result in
switch result {
case .failure(let dataStoreError):
completion(.failure(dataStoreError))
case .success(let mutationEvent):
self.log.verbose("\(#function) successfully submitted to sync engine \(mutationEvent)")
completion(.successfulVoid)
}
}
submitToSyncEngine(mutationEvent: mutationEvent,
syncEngine: syncEngine,
completion: mutationEventCallback)
}
@available(iOS 13.0, *)
//Note: this function looks a lot like syncDeletion, but will change when
// we start to pass in the predicate
private func syncDeletions<M: Model>(of modelType: M.Type,
modelSchema: ModelSchema,
withModels models: [M],
predicate: QueryPredicate? = nil,
syncEngine: RemoteSyncEngineBehavior,
completion: @escaping DataStoreCallback<Void>) {
var mutationEvents: Set<Model.Identifier> = []
var graphQLFilterJSON: String?
if let predicate = predicate {
do {
graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate)
} catch {
let dataStoreError = DataStoreError(error: error)
completion(.failure(dataStoreError))
return
}
}
for model in models {
let mutationEvent: MutationEvent
do {
mutationEvent = try MutationEvent(model: model,
modelSchema: modelSchema,
mutationType: .delete,
graphQLFilterJSON: graphQLFilterJSON)
} catch {
let dataStoreError = DataStoreError(error: error)
completion(.failure(dataStoreError))
return
}
let mutationEventCallback: DataStoreCallback<MutationEvent> = { result in
switch result {
case .failure(let dataStoreError):
completion(.failure(dataStoreError))
case .success(let mutationEvent):
mutationEvents.insert(mutationEvent.modelId)
self.log.verbose("\(#function) successfully submitted to sync engine \(mutationEvent)")
if mutationEvents.count == models.count {
completion(.successfulVoid)
}
}
}
submitToSyncEngine(mutationEvent: mutationEvent,
syncEngine: syncEngine,
completion: mutationEventCallback)
}
}
@available(iOS 13.0, *)
private func syncMutation<M: Model>(of savedModel: M,
modelSchema: ModelSchema,
mutationType: MutationEvent.MutationType,
predicate: QueryPredicate? = nil,
syncEngine: RemoteSyncEngineBehavior,
completion: @escaping DataStoreCallback<M>) {
let mutationEvent: MutationEvent
do {
var graphQLFilterJSON: String?
if let predicate = predicate {
graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate)
}
mutationEvent = try MutationEvent(model: savedModel,
modelSchema: modelSchema,
mutationType: mutationType,
graphQLFilterJSON: graphQLFilterJSON)
} catch {
let dataStoreError = DataStoreError(error: error)
completion(.failure(dataStoreError))
return
}
let mutationEventCallback: DataStoreCallback<MutationEvent> = { result in
switch result {
case .failure(let dataStoreError):
completion(.failure(dataStoreError))
case .success(let mutationEvent):
self.log.verbose("\(#function) successfully submitted to sync engine \(mutationEvent)")
completion(.success(savedModel))
}
}
submitToSyncEngine(mutationEvent: mutationEvent,
syncEngine: syncEngine,
completion: mutationEventCallback)
}
@available(iOS 13.0, *)
private func submitToSyncEngine(mutationEvent: MutationEvent,
syncEngine: RemoteSyncEngineBehavior,
completion: @escaping DataStoreCallback<MutationEvent>) {
var mutationQueueSink: AnyCancellable?
mutationQueueSink = syncEngine
.submit(mutationEvent)
.sink(
receiveCompletion: { futureCompletion in
switch futureCompletion {
case .failure(let error):
completion(.failure(causedBy: error))
case .finished:
self.log.verbose("\(#function) Received successful completion")
}
mutationQueueSink?.cancel()
mutationQueueSink = nil
}, receiveValue: { mutationEvent in
self.log.verbose("\(#function) saved mutation event: \(mutationEvent)")
completion(.success(mutationEvent))
})
}
}
extension StorageEngine: DefaultLogger { }
| 40.252595 | 125 | 0.539199 |
d51ee0e734aa46316c7d269ba307fcfae789afd0 | 2,874 | //
// ComplicationController.swift
// BusFinder Watch App Extension
//
// Created by John Forde on 11/1/18.
// Copyright © 2018 4DWare. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: Register
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Swift.Void) {
if complication.family == .utilitarianLarge {
let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat()
largeFlat.textProvider = CLKSimpleTextProvider(text: "[052] 19:52")
handler(largeFlat)
} else if complication.family == .modularLarge {
let largeFlat = CLKComplicationTemplateModularLargeStandardBody()
largeFlat.headerTextProvider = CLKSimpleTextProvider(text: "Bus Finder")
largeFlat.headerTextProvider.tintColor = UIColor(red: 250/255, green: 17/255, blue: 79/255, alpha: 1)
largeFlat.body1TextProvider = CLKSimpleTextProvider(text: "Farmers")
largeFlat.body2TextProvider = CLKSimpleTextProvider(text: "[052] 19:52")
handler(largeFlat)
}
}
// MARK: Provide Data
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Swift.Void) {
let firstService = MetLinkApi.loadFirstService()
if complication.family == .utilitarianLarge {
let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat()
largeFlat.textProvider = CLKSimpleTextProvider(text: "[\(firstService.ServiceID)] \(getTimeFromDateString(from: firstService.ExpectedDeparture)) \(firstService.DepartureStatus ?? firstService.AimedArrival ?? "No Data")")
handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: largeFlat))
} else if complication.family == .modularLarge {
let largeFlat = CLKComplicationTemplateModularLargeStandardBody()
largeFlat.headerTextProvider = CLKSimpleTextProvider(text: "Bus Finder")
largeFlat.headerTextProvider.tintColor = UIColor(red: 250/255, green: 17/255, blue: 79/255, alpha: 1)
largeFlat.body1TextProvider = CLKSimpleTextProvider(text: "[\(firstService.ServiceID)] \(getTimeFromDateString(from: firstService.ExpectedDeparture))")
largeFlat.body2TextProvider = CLKSimpleTextProvider(text: "\(firstService.DepartureStatus ?? "No Data")" )
handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: largeFlat))
}
}
func reloadData() {
let server = CLKComplicationServer.sharedInstance()
guard let complications = server.activeComplications, complications.count > 0 else { return }
for complication in complications {
server.reloadTimeline(for: complication)
}
}
// MARK: Time Travel
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Swift.Void) {
handler([])
}
}
| 45.619048 | 223 | 0.776618 |
e9c323e02f1b2632634ca16179e8d5998735a8b7 | 1,027 | //
// AlbumArt.swift
// MusicApp
//
// Created by ozan honamlioglu on 29.01.2021.
//
import SwiftUI
struct AlbumArt: View {
var album: Album
var isWithText: Bool
var body: some View {
ZStack(alignment: .bottom, content: {
Image(album.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 170, height: 200, alignment: .center)
if(isWithText) {
ZStack {
BlurEffect(style: .light)
Text(album.name).foregroundColor(.white)
}.frame(height: 60, alignment: .center)
}
}).frame(width: 170, height: 200, alignment: .center).clipped().cornerRadius(20).shadow(radius: 10).padding(20)
}
}
struct AlbumArt_Previews: PreviewProvider {
static var previews: some View {
Group {
AlbumArt(album: dummyAlbum[0], isWithText: true)
.previewDevice("iPhone 12 mini")
}
}
}
| 26.333333 | 119 | 0.542356 |
e0d96e23e3c37dc8ead4c42a7e6a842cebad6000 | 206 | //
// PrintFn.swift
// UltraProject1
//
// Created by leeesangheee on 2021/09/28.
//
import Foundation
public func print(_ object: Any) {
#if DEBUG
Swift.print("DEBUG: \(object)")
#endif
}
| 13.733333 | 42 | 0.631068 |
218bd1d4a8762573750fb521ae0c2a009934066c | 860 | //
// SCIndexesTableViewCell.swift
// MyFinanceInfo
//
// Created by Stephen Cao on 19/7/19.
// Copyright © 2019 Stephen Cao. All rights reserved.
//
import UIKit
class SCIndexesTableViewCell: UITableViewCell {
var viewModel: SCIndexesViewModel?{
didSet{
indexNameLabel.text = viewModel?.indexName
priceLabel.text = viewModel?.price
changeLabel.text = viewModel?.changes
changeLabel.textColor = viewModel?.changesLabelColor
changePercentageLabel.text = viewModel?.changesPercentage
changePercentageLabel.textColor = viewModel?.changesPercentageLabelColor
}
}
@IBOutlet weak var indexNameLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var changeLabel: UILabel!
@IBOutlet weak var changePercentageLabel: UILabel!
}
| 30.714286 | 84 | 0.694186 |
ef9e6cba7a7adb90a450912cdf07d0e82e841f55 | 75,684 | //===--- UnicodeDecoders.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-build-swift %s -swift-version 3 -g -Onone -o %T/UnicodeDecoders
// RUN: %target-run %T/UnicodeDecoders
// REQUIRES: executable_test
// Benchmarking: use the following script with your swift-4-enabled swiftc.
// The BASELINE timings come from the existing standard library Codecs
/*
for x in BASELINE FORWARD REVERSE SEQUENCE COLLECTION REVERSE_COLLECTION ; do
echo $x
swiftc -DBENCHMARK -D$x -O -swift-version 4 UnicodeDecoders.swift -o /tmp/u3-$x
for i in {1..3}; do
(time nice -19 /tmp/u3-$x) 2>&1 | grep user
done
done
*/
//===----------------------------------------------------------------------===//
extension Unicode.Scalar {
// Hack providing an efficient API that is available to the standard library
@_versioned
@inline(__always)
init(_unchecked x: UInt32) { self = unsafeBitCast(x, to: Unicode.Scalar.self) }
}
//===----------------------------------------------------------------------===//
extension Unicode {
struct DefaultScalarView<
CodeUnits: BidirectionalCollection,
Encoding: Unicode.Encoding
> where CodeUnits.Element == Encoding.CodeUnit {
var codeUnits: CodeUnits
init(
_ codeUnits: CodeUnits,
fromEncoding _: Encoding.Type = Encoding.self) {
self.codeUnits = codeUnits
}
}
}
extension Unicode.DefaultScalarView : Sequence {
struct Iterator {
var parsing: Unicode._ParsingIterator<
CodeUnits.Iterator, Encoding.ForwardParser>
}
func makeIterator() -> Iterator {
return Iterator(
parsing: Unicode._ParsingIterator(
codeUnits: codeUnits.makeIterator(),
parser: Encoding.ForwardParser()
))
}
}
extension Unicode.DefaultScalarView.Iterator : IteratorProtocol, Sequence {
mutating func next() -> Unicode.Scalar? {
return parsing.next().map { Encoding.decode($0) }
}
}
extension Unicode.DefaultScalarView {
struct Index {
var codeUnitIndex: CodeUnits.Index
var scalar: Unicode.Scalar
var stride: UInt8
}
}
extension Unicode.DefaultScalarView.Index : Comparable {
@inline(__always)
public static func < (
lhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index,
rhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index
) -> Bool {
return lhs.codeUnitIndex < rhs.codeUnitIndex
}
@inline(__always)
public static func == (
lhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index,
rhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index
) -> Bool {
return lhs.codeUnitIndex == rhs.codeUnitIndex
}
}
extension Unicode.DefaultScalarView : Collection {
public var startIndex: Index {
@inline(__always)
get {
return index(
after: Index(
codeUnitIndex: codeUnits.startIndex,
scalar: Unicode.Scalar(_unchecked: 0),
stride: 0)
)
}
}
public var endIndex: Index {
@inline(__always)
get {
return Index(
codeUnitIndex: codeUnits.endIndex,
scalar: Unicode.Scalar(_unchecked: 0),
stride: 0)
}
}
public subscript(i: Index) -> Unicode.Scalar {
@inline(__always) get { return i.scalar }
}
@inline(__always)
public func index(after i: Index) -> Index {
let nextPosition = codeUnits.index(
i.codeUnitIndex, offsetBy: numericCast(i.stride))
var i = IndexingIterator(
_elements: codeUnits, _position: nextPosition
)
var d = Encoding.ForwardParser()
switch d.parseScalar(from: &i) {
case .valid(let scalarContent):
return Index(
codeUnitIndex: nextPosition,
scalar: Encoding.decode(scalarContent),
stride: numericCast(scalarContent.count))
case .error(let stride):
return Index(
codeUnitIndex: nextPosition,
scalar: Unicode.Scalar(_unchecked: 0xfffd),
stride: numericCast(stride))
case .emptyInput:
return endIndex
}
}
}
extension Unicode.DefaultScalarView : BidirectionalCollection {
@inline(__always)
public func index(before i: Index) -> Index {
var parser = Encoding.ReverseParser()
var more = _ReverseIndexingIterator(
_elements: codeUnits, _position: i.codeUnitIndex)
switch parser.parseScalar(from: &more) {
case .valid(let scalarContent):
let d: CodeUnits.IndexDistance = -numericCast(scalarContent.count)
return Index(
codeUnitIndex: codeUnits.index(i.codeUnitIndex, offsetBy: d),
scalar: Encoding.decode(scalarContent),
stride: numericCast(scalarContent.count))
case .error(let stride):
let d: CodeUnits.IndexDistance = -numericCast(stride)
return Index(
codeUnitIndex: codeUnits.index(i.codeUnitIndex, offsetBy: d) ,
scalar: Unicode.Scalar(_unchecked: 0xfffd),
stride: numericCast(stride))
case .emptyInput: fatalError("index out of bounds.")
}
}
}
#if !BENCHMARK
//===--- testing ----------------------------------------------------------===//
import StdlibUnittest
import SwiftPrivate
func utf32<S : StringProtocol>(_ s: S) -> [UInt32] {
return s.unicodeScalars.map { $0.value }
}
func checkStringProtocol<S : StringProtocol, Encoding: Unicode.Encoding>(
_ s: S,
_ utfStr: [Encoding.CodeUnit],
encodedAs: Encoding.Type,
expectingUTF32 expected: [UInt32]
) {
expectEqualSequence(
expected, utf32(S(decoding: utfStr, as: Encoding.self)),
"\(S.self) init(decoding:as:)")
if !utfStr.contains(0) {
if Encoding.self == Unicode.UTF8.self {
var ntbs = utfStr.map { CChar(truncatingIfNeeded: $0) }
ntbs.append(0)
expectEqualSequence(
expected, utf32(S(cString: ntbs)), "\(S.self) init(cString:)")
}
var ntbs = Array(utfStr); ntbs.append(0)
expectEqualSequence(
expected, utf32(S(decodingCString: ntbs, as: Encoding.self)),
"\(S.self) init(cString:encoding:)"
)
s.withCString {
expectEqual(s, S(cString: $0), "\(S.self) withCString(_:)")
}
s.withCString(encodedAs: Encoding.self) {
expectEqual(s, S(decodingCString: $0, as: Encoding.self),
"\(S.self) withCString(encoding:_:)")
}
}
}
func checkDecodeUTF<Codec : UnicodeCodec>(
_ codec: Codec.Type, _ expectedHead: [UInt32],
_ expectedRepairedTail: [UInt32], _ utfStr: [Codec.CodeUnit]
) -> AssertionResult {
var decoded = [UInt32]()
var expected = expectedHead
func output(_ scalar: UInt32) {
decoded.append(scalar)
expectEqual(
Unicode.Scalar(scalar),
Codec.decode(Codec.encode(Unicode.Scalar(scalar)!)!))
}
func output1(_ scalar: Unicode.Scalar) {
decoded.append(scalar.value)
expectEqual(scalar, Codec.decode(Codec.encode(scalar)!))
}
var result = assertionSuccess()
func check<C: Collection>(_ expected: C, _ description: String)
where C.Element == UInt32
{
if !expected.elementsEqual(decoded) {
if result.description == "" { result = assertionFailure() }
result = result.withDescription(" [\(description)]\n")
.withDescription("expected: \(asHex(expectedHead))\n")
.withDescription("actual: \(asHex(decoded))")
}
decoded.removeAll(keepingCapacity: true)
}
//===--- Tests without repairs ------------------------------------------===//
do {
let iterator = utfStr.makeIterator()
_ = transcode(
iterator, from: codec, to: Unicode.UTF32.self,
stoppingOnError: true, into: output)
}
check(expected, "legacy, repairing: false")
do {
var iterator = utfStr.makeIterator()
let errorCount = Codec.ForwardParser._decode(
&iterator, repairingIllFormedSequences: false, into: output1)
expectEqual(expectedRepairedTail.isEmpty ? 0 : 1, errorCount)
}
check(expected, "forward, repairing: false")
do {
var iterator = utfStr.reversed().makeIterator()
let errorCount = Codec.ReverseParser._decode(
&iterator, repairingIllFormedSequences: false, into: output1)
if expectedRepairedTail.isEmpty {
expectEqual(0, errorCount)
check(expected.reversed(), "reverse, repairing: false")
}
else {
expectEqual(1, errorCount)
let x = (expected + expectedRepairedTail).reversed()
expectTrue(
x.starts(with: decoded),
"reverse, repairing: false\n\t\(Array(x)) does not start with \(decoded)")
decoded.removeAll(keepingCapacity: true)
}
}
//===--- Tests with repairs ------------------------------------------===//
expected += expectedRepairedTail
do {
let iterator = utfStr.makeIterator()
_ = transcode(iterator, from: codec, to: Unicode.UTF32.self,
stoppingOnError: false, into: output)
}
check(expected, "legacy, repairing: true")
do {
var iterator = utfStr.makeIterator()
let errorCount = Codec.ForwardParser._decode(
&iterator, repairingIllFormedSequences: true, into: output1)
if expectedRepairedTail.isEmpty { expectEqual(0, errorCount) }
else { expectNotEqual(0, errorCount) }
}
check(expected, "forward, repairing: true")
do {
var iterator = utfStr.reversed().makeIterator()
let errorCount = Codec.ReverseParser._decode(
&iterator, repairingIllFormedSequences: true, into: output1)
if expectedRepairedTail.isEmpty { expectEqual(0, errorCount) }
else { expectNotEqual(0, errorCount) }
}
check(expected.reversed(), "reverse, repairing: true")
//===--- String/Substring Construction and C-String interop -------------===//
do {
let s = String(decoding: utfStr, as: Codec.self)
checkStringProtocol(
s, utfStr, encodedAs: Codec.self, expectingUTF32: expected)
}
do {
let s0 = "\n" + String(decoding: utfStr, as: Codec.self) + "\n"
let s = s0.dropFirst().dropLast()
expectEqualSequence(expected, utf32(s), "Sliced Substring")
checkStringProtocol(
s0.dropFirst().dropLast(),
utfStr, encodedAs: Codec.self, expectingUTF32: expected)
}
//===--- Transcoded Scalars ---------------------------------------------===//
for x in decoded.lazy.map({ Unicode.Scalar($0)! }) {
expectEqualSequence(
Unicode.UTF8.encode(x)!,
Unicode.UTF8.transcode(
Codec.encode(x)!, from: Codec.self)!
)
expectEqualSequence(
Unicode.UTF16.encode(x)!,
Unicode.UTF16.transcode(
Codec.encode(x)!, from: Codec.self)!
)
expectEqualSequence(
Unicode.UTF32.encode(x)!,
Unicode.UTF32.transcode(
Codec.encode(x)!, from: Codec.self)!
)
}
//===--- Scalar View ----------------------------------------------------===//
let scalars = Unicode.DefaultScalarView(utfStr, fromEncoding: Codec.self)
expectEqualSequence(expected, scalars.map { $0.value })
expectEqualSequence(
expected.reversed(),
scalars.reversed().map { $0.value })
do {
var x = scalars.makeIterator()
var j = scalars.startIndex
while (j != scalars.endIndex) {
expectEqual(x.next()!, scalars[j])
j = scalars.index(after: j)
}
expectNil(x.next())
}
return result
}
func checkDecodeUTF8(
_ expectedHead: [UInt32],
_ expectedRepairedTail: [UInt32], _ utf8Str: [UInt8]
) -> AssertionResult {
return checkDecodeUTF(Unicode.UTF8.self, expectedHead, expectedRepairedTail, utf8Str)
}
func checkDecodeUTF16(
_ expectedHead: [UInt32],
_ expectedRepairedTail: [UInt32], _ utf16Str: [UInt16]
) -> AssertionResult {
return checkDecodeUTF(Unicode.UTF16.self, expectedHead, expectedRepairedTail,
utf16Str)
}
func checkDecodeUTF32(
_ expectedHead: [UInt32],
_ expectedRepairedTail: [UInt32], _ utf32Str: [UInt32]
) -> AssertionResult {
return checkDecodeUTF(Unicode.UTF32.self, expectedHead, expectedRepairedTail,
utf32Str)
}
func checkEncodeUTF8(_ expected: [UInt8],
_ scalars: [UInt32]) -> AssertionResult {
var encoded = [UInt8]()
let output: (UInt8) -> Void = { encoded.append($0) }
let iterator = scalars.makeIterator()
let hadError = transcode(
iterator,
from: Unicode.UTF32.self,
to: Unicode.UTF8.self,
stoppingOnError: true,
into: output)
expectFalse(hadError)
if expected != encoded {
return assertionFailure()
.withDescription("\n")
.withDescription("expected: \(asHex(expected))\n")
.withDescription("actual: \(asHex(encoded))")
}
return assertionSuccess()
}
//===----------------------------------------------------------------------===//
var UTF32Decoder = TestSuite("UTF32Decoder")
UTF32Decoder.test("Empty") {
expectTrue(checkDecodeUTF32([], [], []))
}
UTF32Decoder.test("SmokeTest") {
// U+0041 LATIN CAPITAL LETTER A
expectTrue(checkDecodeUTF32([ 0x0041 ], [], [ 0x0000_0041 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
expectTrue(checkDecodeUTF32(
[ 0x0041, 0x0042 ], [],
[ 0x0000_0041, 0x0000_0042 ]))
// U+0000 NULL
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0000 NULL
expectTrue(checkDecodeUTF32(
[ 0x0000, 0x0041, 0x0042, 0x0000 ], [],
[ 0x0000_0000, 0x0000_0041, 0x0000_0042, 0x0000_0000 ]))
// U+0283 LATIN SMALL LETTER ESH
expectTrue(checkDecodeUTF32([ 0x0283 ], [], [ 0x0000_0283 ]))
// U+03BA GREEK SMALL LETTER KAPPA
// U+1F79 GREEK SMALL LETTER OMICRON WITH OXIA
// U+03C3 GREEK SMALL LETTER SIGMA
// U+03BC GREEK SMALL LETTER MU
// U+03B5 GREEK SMALL LETTER EPSILON
expectTrue(checkDecodeUTF32(
[ 0x03ba, 0x1f79, 0x03c3, 0x03bc, 0x03b5 ], [],
[ 0x0000_03ba, 0x0000_1f79, 0x0000_03c3, 0x0000_03bc, 0x0000_03b5 ]))
// U+4F8B CJK UNIFIED IDEOGRAPH-4F8B
// U+6587 CJK UNIFIED IDEOGRAPH-6587
expectTrue(checkDecodeUTF32(
[ 0x4f8b, 0x6587 ], [],
[ 0x0000_4f8b, 0x0000_6587 ]))
// U+D55C HANGUL SYLLABLE HAN
// U+AE00 HANGUL SYLLABLE GEUL
expectTrue(checkDecodeUTF32(
[ 0xd55c, 0xae00 ], [],
[ 0x0000_d55c, 0x0000_ae00 ]))
// U+1112 HANGUL CHOSEONG HIEUH
// U+1161 HANGUL JUNGSEONG A
// U+11AB HANGUL JONGSEONG NIEUN
// U+1100 HANGUL CHOSEONG KIYEOK
// U+1173 HANGUL JUNGSEONG EU
// U+11AF HANGUL JONGSEONG RIEUL
expectTrue(checkDecodeUTF32(
[ 0x1112, 0x1161, 0x11ab, 0x1100, 0x1173, 0x11af ], [],
[ 0x0000_1112, 0x0000_1161, 0x0000_11ab, 0x0000_1100, 0x0000_1173,
0x0000_11af ]))
// U+D7FF (unassigned)
expectTrue(checkDecodeUTF16([ 0xd7ff ], [], [ 0x0000_d7ff ]))
// U+E000 (private use)
expectTrue(checkDecodeUTF16([ 0xe000 ], [], [ 0x0000_e000 ]))
// U+FFFD REPLACEMENT CHARACTER
expectTrue(checkDecodeUTF16([ 0xfffd ], [], [ 0x0000_fffd ]))
// U+FFFF (noncharacter)
expectTrue(checkDecodeUTF16([ 0xffff ], [], [ 0x0000_ffff ]))
// U+10000 LINEAR B SYLLABLE B008 A
expectTrue(checkDecodeUTF32([ 0x00010000 ], [], [ 0x0001_0000 ]))
// U+10100 AEGEAN WORD SEPARATOR LINE
expectTrue(checkDecodeUTF32([ 0x00010100 ], [], [ 0x0001_0100 ]))
// U+103FF (unassigned)
expectTrue(checkDecodeUTF32([ 0x000103ff ], [], [ 0x0001_03ff ]))
// U+1D800 (unassigned)
expectTrue(checkDecodeUTF32([ 0x0001d800 ], [], [ 0x0001_d800 ]))
// U+E0000 (unassigned)
expectTrue(checkDecodeUTF32([ 0x000e0000 ], [], [ 0x000e_0000 ]))
// U+E0100 VARIATION SELECTOR-17
expectTrue(checkDecodeUTF32([ 0x000e0100 ], [], [ 0x000e_0100 ]))
// U+E03FF (unassigned)
expectTrue(checkDecodeUTF32([ 0x000e03ff ], [], [ 0x000e_03ff ]))
// U+10FC00 (private use)
expectTrue(checkDecodeUTF32([ 0x0010fc00 ], [], [ 0x0010_fc00 ]))
// U+10FD00 (private use)
expectTrue(checkDecodeUTF32([ 0x0010fd00 ], [], [ 0x0010_fd00 ]))
// U+10FFFF (private use, noncharacter)
expectTrue(checkDecodeUTF32([ 0x0010ffff ], [], [ 0x0010_ffff ]))
}
UTF32Decoder.test("IllFormed") {
// U+D800 (high-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_d800 ]))
// U+DB40 (high-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_db40 ]))
// U+DBFF (high-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_dbff ]))
// U+DC00 (low-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_dc00 ]))
// U+DD00 (low-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_dd00 ]))
// U+DFFF (low-surrogate)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0000_dfff ]))
// U+110000 (invalid)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0011_0000 ]))
// U+1000000 (invalid)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x0100_0000 ]))
// U+80000000 (invalid)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0x8000_0000 ]))
// U+FFFF0000 (invalid)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0xffff_0000 ]))
// U+FFFFFFFF (invalid)
expectTrue(checkDecodeUTF32([], [ 0xfffd ], [ 0xffff_ffff ]))
}
var UTF8Decoder = TestSuite("UTF8Decoder")
//===----------------------------------------------------------------------===//
public struct UTFTest {
public struct Flags : OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let utf8IsInvalid = Flags(rawValue: 1 << 0)
public static let utf16IsInvalid = Flags(rawValue: 1 << 1)
}
public let string: String
public let utf8: [UInt8]
public let utf16: [UInt16]
public let unicodeScalars: [Unicode.Scalar]
public let unicodeScalarsRepairedTail: [Unicode.Scalar]
public let flags: Flags
public let loc: SourceLoc
public var utf32: [UInt32] {
return unicodeScalars.map(UInt32.init)
}
public var utf32RepairedTail: [UInt32] {
return unicodeScalarsRepairedTail.map(UInt32.init)
}
public init(
string: String,
utf8: [UInt8],
utf16: [UInt16],
scalars: [UInt32],
scalarsRepairedTail: [UInt32] = [],
flags: Flags = [],
file: String = #file, line: UInt = #line
) {
self.string = string
self.utf8 = utf8
self.utf16 = utf16
self.unicodeScalars = scalars.map { Unicode.Scalar($0)! }
self.unicodeScalarsRepairedTail =
scalarsRepairedTail.map { Unicode.Scalar($0)! }
self.flags = flags
self.loc = SourceLoc(file, line, comment: "test data")
}
}
public var utfTests: [UTFTest] = []
//
// Empty sequence.
//
utfTests.append(
UTFTest(
string: "",
utf8: [],
utf16: [],
scalars: []))
//
// 1-byte sequences.
//
// U+0000 NULL
utfTests.append(
UTFTest(
string: "\u{0000}",
utf8: [ 0x00 ],
utf16: [ 0x00 ],
scalars: [ 0x00 ]))
// U+0041 LATIN CAPITAL LETTER A
utfTests.append(
UTFTest(
string: "A",
utf8: [ 0x41 ],
utf16: [ 0x41 ],
scalars: [ 0x41 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
utfTests.append(
UTFTest(
string: "AB",
utf8: [ 0x41, 0x42 ],
utf16: [ 0x41, 0x42 ],
scalars: [ 0x41, 0x42 ]))
// U+0061 LATIN SMALL LETTER A
// U+0062 LATIN SMALL LETTER B
// U+0063 LATIN SMALL LETTER C
utfTests.append(
UTFTest(
string: "ABC",
utf8: [ 0x41, 0x42, 0x43 ],
utf16: [ 0x41, 0x42, 0x43 ],
scalars: [ 0x41, 0x42, 0x43 ]))
// U+0000 NULL
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0000 NULL
utfTests.append(
UTFTest(
string: "\u{0000}AB\u{0000}",
utf8: [ 0x00, 0x41, 0x42, 0x00 ],
utf16: [ 0x00, 0x41, 0x42, 0x00 ],
scalars: [ 0x00, 0x41, 0x42, 0x00 ]))
// U+007F DELETE
utfTests.append(
UTFTest(
string: "\u{007F}",
utf8: [ 0x7F ],
utf16: [ 0x7F ],
scalars: [ 0x7F ]))
//
// 2-byte sequences.
//
// U+0283 LATIN SMALL LETTER ESH
utfTests.append(
UTFTest(
string: "\u{0283}",
utf8: [ 0xCA, 0x83 ],
utf16: [ 0x0283 ],
scalars: [ 0x0283 ]))
// U+03BA GREEK SMALL LETTER KAPPA
// U+1F79 GREEK SMALL LETTER OMICRON WITH OXIA
// U+03C3 GREEK SMALL LETTER SIGMA
// U+03BC GREEK SMALL LETTER MU
// U+03B5 GREEK SMALL LETTER EPSILON
utfTests.append(
UTFTest(
string: "\u{03BA}\u{1F79}\u{03C3}\u{03BC}\u{03B5}",
utf8: [ 0xCE, 0xBA, 0xE1, 0xBD, 0xB9, 0xCF, 0x83, 0xCE, 0xBC, 0xCE, 0xB5 ],
utf16: [ 0x03BA, 0x1F79, 0x03C3, 0x03BC, 0x03B5 ],
scalars: [ 0x03BA, 0x1F79, 0x03C3, 0x03BC, 0x03B5 ]))
// U+0430 CYRILLIC SMALL LETTER A
// U+0431 CYRILLIC SMALL LETTER BE
// U+0432 CYRILLIC SMALL LETTER VE
utfTests.append(
UTFTest(
string: "\u{0430}\u{0431}\u{0432}",
utf8: [ 0xD0, 0xB0, 0xD0, 0xB1, 0xD0, 0xB2 ],
utf16: [ 0x0430, 0x0431, 0x0432 ],
scalars: [ 0x0430, 0x0431, 0x0432 ]))
//
// 3-byte sequences.
//
// U+4F8B CJK UNIFIED IDEOGRAPH-4F8B
// U+6587 CJK UNIFIED IDEOGRAPH-6587
utfTests.append(
UTFTest(
string: "\u{4F8b}\u{6587}",
utf8: [ 0xE4, 0xBE, 0x8B, 0xE6, 0x96, 0x87 ],
utf16: [ 0x4F8B, 0x6587 ],
scalars: [ 0x4F8B, 0x6587 ]))
// U+D55C HANGUL SYLLABLE HAN
// U+AE00 HANGUL SYLLABLE GEUL
utfTests.append(
UTFTest(
string: "\u{d55c}\u{ae00}",
utf8: [ 0xED, 0x95, 0x9C, 0xEA, 0xB8, 0x80 ],
utf16: [ 0xD55C, 0xAE00 ],
scalars: [ 0xD55C, 0xAE00 ]))
// U+1112 HANGUL CHOSEONG HIEUH
// U+1161 HANGUL JUNGSEONG A
// U+11AB HANGUL JONGSEONG NIEUN
// U+1100 HANGUL CHOSEONG KIYEOK
// U+1173 HANGUL JUNGSEONG EU
// U+11AF HANGUL JONGSEONG RIEUL
utfTests.append(
UTFTest(
string: "\u{1112}\u{1161}\u{11ab}\u{1100}\u{1173}\u{11af}",
utf8:
[ 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xA1, 0xE1, 0x86, 0xAB,
0xE1, 0x84, 0x80, 0xE1, 0x85, 0xB3, 0xE1, 0x86, 0xAF ],
utf16: [ 0x1112, 0x1161, 0x11AB, 0x1100, 0x1173, 0x11AF ],
scalars: [ 0x1112, 0x1161, 0x11AB, 0x1100, 0x1173, 0x11AF ]))
// U+3042 HIRAGANA LETTER A
// U+3044 HIRAGANA LETTER I
// U+3046 HIRAGANA LETTER U
// U+3048 HIRAGANA LETTER E
// U+304A HIRAGANA LETTER O
utfTests.append(
UTFTest(
string: "\u{3042}\u{3044}\u{3046}\u{3048}\u{304a}",
utf8:
[ 0xE3, 0x81, 0x82, 0xE3, 0x81, 0x84, 0xE3, 0x81, 0x86,
0xE3, 0x81, 0x88, 0xE3, 0x81, 0x8A ],
utf16: [ 0x3042, 0x3044, 0x3046, 0x3048, 0x304A ],
scalars: [ 0x3042, 0x3044, 0x3046, 0x3048, 0x304A ]))
// U+D7FF (unassigned)
utfTests.append(
UTFTest(
string: "\u{D7FF}",
utf8: [ 0xED, 0x9F, 0xBF ],
utf16: [ 0xD7FF ],
scalars: [ 0xD7FF ]))
// U+E000 (private use)
utfTests.append(
UTFTest(
string: "\u{E000}",
utf8: [ 0xEE, 0x80, 0x80 ],
utf16: [ 0xE000 ],
scalars: [ 0xE000 ]))
// U+FFFD REPLACEMENT CHARACTER
utfTests.append(
UTFTest(
string: "\u{FFFD}",
utf8: [ 0xEF, 0xBF, 0xBD ],
utf16: [ 0xFFFD ],
scalars: [ 0xFFFD ]))
// U+FFFF (noncharacter)
utfTests.append(
UTFTest(
string: "\u{FFFF}",
utf8: [ 0xEF, 0xBF, 0xBF ],
utf16: [ 0xFFFF ],
scalars: [ 0xFFFF ]))
//
// 4-byte sequences.
//
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "\u{1F425}",
utf8: [ 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0xD83D, 0xDC25 ],
scalars: [ 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "A\u{1F425}",
utf8: [ 0x41, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "AB\u{1F425}",
utf8: [ 0x41, 0x42, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABC\u{1F425}",
utf8: [ 0x41, 0x42, 0x43, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0x43, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x43, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCD\u{1F425}",
utf8: [ 0x41, 0x42, 0x43, 0x44, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0x43, 0x44, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x43, 0x44, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+0045 LATIN CAPITAL LETTER E
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCDE\u{1F425}",
utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+0045 LATIN CAPITAL LETTER E
// U+0046 LATIN CAPITAL LETTER F
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCDEF\u{1F425}",
utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+0045 LATIN CAPITAL LETTER E
// U+0046 LATIN CAPITAL LETTER F
// U+0047 LATIN CAPITAL LETTER G
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCDEFG\u{1F425}",
utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0xF0, 0x9F, 0x90, 0xA5 ],
utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0xD83D, 0xDC25 ],
scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+0045 LATIN CAPITAL LETTER E
// U+0046 LATIN CAPITAL LETTER F
// U+0047 LATIN CAPITAL LETTER G
// U+0048 LATIN CAPITAL LETTER H
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCDEFGH\u{1F425}",
utf8:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0xF0, 0x9F, 0x90, 0xA5 ],
utf16:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0xD83D, 0xDC25 ],
scalars:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x0001_F425 ]))
// U+0041 LATIN CAPITAL LETTER A
// U+0042 LATIN CAPITAL LETTER B
// U+0043 LATIN CAPITAL LETTER C
// U+0044 LATIN CAPITAL LETTER D
// U+0045 LATIN CAPITAL LETTER E
// U+0046 LATIN CAPITAL LETTER F
// U+0047 LATIN CAPITAL LETTER G
// U+0048 LATIN CAPITAL LETTER H
// U+0049 LATIN CAPITAL LETTER I
// U+1F425 FRONT-FACING BABY CHICK
utfTests.append(
UTFTest(
string: "ABCDEFGHI\u{1F425}",
utf8:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0xF0, 0x9F, 0x90, 0xA5 ],
utf16:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0xD83D, 0xDC25 ],
scalars:
[ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x0001_F425 ]))
// U+10000 LINEAR B SYLLABLE B008 A
utfTests.append(
UTFTest(
string: "\u{10000}",
utf8: [ 0xF0, 0x90, 0x80, 0x80 ],
utf16: [ 0xD800, 0xDC00 ],
scalars: [ 0x0001_0000 ]))
// U+10100 AEGEAN WORD SEPARATOR LINE
utfTests.append(
UTFTest(
string: "\u{10100}",
utf8: [ 0xF0, 0x90, 0x84, 0x80 ],
utf16: [ 0xD800, 0xDD00 ],
scalars: [ 0x0001_0100 ]))
// U+103FF (unassigned)
utfTests.append(
UTFTest(
string: "\u{103FF}",
utf8: [ 0xF0, 0x90, 0x8F, 0xBF ],
utf16: [ 0xD800, 0xDFFF ],
scalars: [ 0x0001_03FF ]))
// U+E0000 (unassigned)
utfTests.append(
UTFTest(
string: "\u{E0000}",
utf8: [ 0xF3, 0xA0, 0x80, 0x80 ],
utf16: [ 0xDB40, 0xDC00 ],
scalars: [ 0x000E_0000 ]))
// U+E0100 VARIATION SELECTOR-17
utfTests.append(
UTFTest(
string: "\u{E0100}",
utf8: [ 0xF3, 0xA0, 0x84, 0x80 ],
utf16: [ 0xDB40, 0xDD00 ],
scalars: [ 0x000E_0100 ]))
// U+E03FF (unassigned)
utfTests.append(
UTFTest(
string: "\u{E03FF}",
utf8: [ 0xF3, 0xA0, 0x8F, 0xBF ],
utf16: [ 0xDB40, 0xDFFF ],
scalars: [ 0x000E_03FF ]))
// U+10FC00 (private use)
utfTests.append(
UTFTest(
string: "\u{10FC00}",
utf8: [ 0xF4, 0x8F, 0xB0, 0x80 ],
utf16: [ 0xDBFF, 0xDC00 ],
scalars: [ 0x0010_FC00 ]))
// U+10FD00 (private use)
utfTests.append(
UTFTest(
string: "\u{10FD00}",
utf8: [ 0xF4, 0x8F, 0xB4, 0x80 ],
utf16: [ 0xDBFF, 0xDD00 ],
scalars: [ 0x0010_FD00 ]))
// U+10FFFF (private use, noncharacter)
utfTests.append(
UTFTest(
string: "\u{10FFFF}",
utf8: [ 0xF4, 0x8F, 0xBF, 0xBF ],
utf16: [ 0xDBFF, 0xDFFF ],
scalars: [ 0x0010_FFFF ]))
//===----------------------------------------------------------------------===//
UTF8Decoder.test("SmokeTest").forEach(in: utfTests) {
test in
expectTrue(
checkDecodeUTF8(test.utf32, [], test.utf8),
stackTrace: test.loc.withCurrentLoc())
return ()
}
UTF8Decoder.test("FirstPossibleSequence") {
//
// First possible sequence of a certain length
//
// U+0000 NULL
expectTrue(checkDecodeUTF8([ 0x0000 ], [], [ 0x00 ]))
// U+0080 PADDING CHARACTER
expectTrue(checkDecodeUTF8([ 0x0080 ], [], [ 0xc2, 0x80 ]))
// U+0800 SAMARITAN LETTER ALAF
expectTrue(checkDecodeUTF8(
[ 0x0800 ], [],
[ 0xe0, 0xa0, 0x80 ]))
// U+10000 LINEAR B SYLLABLE B008 A
expectTrue(checkDecodeUTF8(
[ 0x10000 ], [],
[ 0xf0, 0x90, 0x80, 0x80 ]))
// U+200000 (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x88, 0x80, 0x80, 0x80 ]))
// U+4000000 (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x84, 0x80, 0x80, 0x80, 0x80 ]))
}
UTF8Decoder.test("LastPossibleSequence") {
//
// Last possible sequence of a certain length
//
// U+007F DELETE
expectTrue(checkDecodeUTF8([ 0x007f ], [], [ 0x7f ]))
// U+07FF (unassigned)
expectTrue(checkDecodeUTF8([ 0x07ff ], [], [ 0xdf, 0xbf ]))
// U+FFFF (noncharacter)
expectTrue(checkDecodeUTF8(
[ 0xffff ], [],
[ 0xef, 0xbf, 0xbf ]))
// U+1FFFFF (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf7, 0xbf, 0xbf, 0xbf ]))
// U+3FFFFFF (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfb, 0xbf, 0xbf, 0xbf, 0xbf ]))
// U+7FFFFFFF (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf ]))
}
UTF8Decoder.test("CodeSpaceBoundaryConditions") {
//
// Other boundary conditions
//
// U+D7FF (unassigned)
expectTrue(checkDecodeUTF8([ 0xd7ff ], [], [ 0xed, 0x9f, 0xbf ]))
// U+E000 (private use)
expectTrue(checkDecodeUTF8([ 0xe000 ], [], [ 0xee, 0x80, 0x80 ]))
// U+FFFD REPLACEMENT CHARACTER
expectTrue(checkDecodeUTF8([ 0xfffd ], [], [ 0xef, 0xbf, 0xbd ]))
// U+10FFFF (noncharacter)
expectTrue(checkDecodeUTF8([ 0x10ffff ], [], [ 0xf4, 0x8f, 0xbf, 0xbf ]))
// U+110000 (invalid)
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf4, 0x90, 0x80, 0x80 ]))
}
UTF8Decoder.test("UnexpectedContinuationBytes") {
//
// Unexpected continuation bytes
//
// A sequence of unexpected continuation bytes that don't follow a first
// byte, every byte is a maximal subpart.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0x80, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xbf, 0x80 ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd ],
[ 0x80, 0xbf, 0x80 ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0x80, 0xbf, 0x80, 0xbf ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0x80, 0xbf, 0x82, 0xbf, 0xaa ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xaa, 0xb0, 0xbb, 0xbf, 0xaa, 0xa0 ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xaa, 0xb0, 0xbb, 0xbf, 0xaa, 0xa0, 0x8f ]))
// All continuation bytes (0x80--0xbf).
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf ]))
}
UTF8Decoder.test("LonelyStartBytes") {
//
// Lonely start bytes
//
// Start bytes of 2-byte sequences (0xc0--0xdf).
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xc0, 0x20, 0xc1, 0x20, 0xc2, 0x20, 0xc3, 0x20,
0xc4, 0x20, 0xc5, 0x20, 0xc6, 0x20, 0xc7, 0x20,
0xc8, 0x20, 0xc9, 0x20, 0xca, 0x20, 0xcb, 0x20,
0xcc, 0x20, 0xcd, 0x20, 0xce, 0x20, 0xcf, 0x20,
0xd0, 0x20, 0xd1, 0x20, 0xd2, 0x20, 0xd3, 0x20,
0xd4, 0x20, 0xd5, 0x20, 0xd6, 0x20, 0xd7, 0x20,
0xd8, 0x20, 0xd9, 0x20, 0xda, 0x20, 0xdb, 0x20,
0xdc, 0x20, 0xdd, 0x20, 0xde, 0x20, 0xdf, 0x20 ]))
// Start bytes of 3-byte sequences (0xe0--0xef).
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xe0, 0x20, 0xe1, 0x20, 0xe2, 0x20, 0xe3, 0x20,
0xe4, 0x20, 0xe5, 0x20, 0xe6, 0x20, 0xe7, 0x20,
0xe8, 0x20, 0xe9, 0x20, 0xea, 0x20, 0xeb, 0x20,
0xec, 0x20, 0xed, 0x20, 0xee, 0x20, 0xef, 0x20 ]))
// Start bytes of 4-byte sequences (0xf0--0xf7).
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020,
0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xf0, 0x20, 0xf1, 0x20, 0xf2, 0x20, 0xf3, 0x20,
0xf4, 0x20, 0xf5, 0x20, 0xf6, 0x20, 0xf7, 0x20 ]))
// Start bytes of 5-byte sequences (0xf8--0xfb).
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0xf9, 0xfa, 0xfb ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xf8, 0x20, 0xf9, 0x20, 0xfa, 0x20, 0xfb, 0x20 ]))
// Start bytes of 6-byte sequences (0xfc--0xfd).
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0xfd ]))
expectTrue(checkDecodeUTF8(
[], [ 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xfc, 0x20, 0xfd, 0x20 ]))
}
UTF8Decoder.test("InvalidStartBytes") {
//
// Other bytes (0xc0--0xc1, 0xfe--0xff).
//
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc1 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfe ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xff ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xc0, 0xc1, 0xfe, 0xff ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfe, 0xfe, 0xff, 0xff ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfe, 0x80, 0x80, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xff, 0x80, 0x80, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ],
[ 0xc0, 0x20, 0xc1, 0x20, 0xfe, 0x20, 0xff, 0x20 ]))
}
UTF8Decoder.test("MissingContinuationBytes") {
//
// Sequences with one continuation byte missing
//
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc2 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xdf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xc2, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xdf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0, 0xa0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe0, 0xa0, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe0, 0xbf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe1, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xec, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe1, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xec, 0xbf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed, 0x9f ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xed, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xed, 0x9f, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xee, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xef, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xee, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xef, 0xbf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0x90, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf0, 0x90, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf0, 0xbf, 0xbf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf1, 0x80, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf3, 0xbf, 0xbf, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x8f, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf4, 0x80, 0x80, 0x41 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf4, 0x8f, 0xbf, 0x41 ]))
// Overlong sequences with one trailing byte missing.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc1 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xe0, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xe0, 0x9f ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x8f, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x80, 0x80, 0x80, 0x80 ]))
// Sequences that represent surrogates with one trailing byte missing.
// High-surrogates
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xa0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xac ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xaf ]))
// Low-surrogates
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xb0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xb4 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xbf ]))
// Ill-formed 4-byte sequences.
// 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+1100xx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf4, 0x90, 0x80 ]))
// U+13FBxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf4, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf5, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf6, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf7, 0x80, 0x80 ]))
// U+1FFBxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf7, 0xbf, 0xbf ]))
// Ill-formed 5-byte sequences.
// 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+2000xx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x88, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0xbf, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf9, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfa, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfb, 0x80, 0x80, 0x80 ]))
// U+3FFFFxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfb, 0xbf, 0xbf, 0xbf ]))
// Ill-formed 6-byte sequences.
// 1111110u 10uuuuuu 10uzzzzz 10zzzyyyy 10yyyyxx 10xxxxxx
// U+40000xx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x84, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0xbf, 0xbf, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0x80, 0x80, 0x80, 0x80 ]))
// U+7FFFFFxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0xbf, 0xbf, 0xbf, 0xbf ]))
//
// Sequences with two continuation bytes missing
//
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0x90 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x8f ]))
// Overlong sequences with two trailing byte missing.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf0, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf0, 0x8f ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x80, 0x80, 0x80 ]))
// Sequences that represent surrogates with two trailing bytes missing.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed ]))
// Ill-formed 4-byte sequences.
// 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+110yxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf4, 0x90 ]))
// U+13Fyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf4, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf5, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf6, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf7, 0x80 ]))
// U+1FFyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf7, 0xbf ]))
// Ill-formed 5-byte sequences.
// 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+200yxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x88, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xf9, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfa, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfb, 0x80, 0x80 ]))
// U+3FFFyxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfb, 0xbf, 0xbf ]))
// Ill-formed 6-byte sequences.
// 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+4000yxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x84, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0xbf, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0x80, 0x80, 0x80 ]))
// U+7FFFFyxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0xbf, 0xbf, 0xbf ]))
//
// Sequences with three continuation bytes missing
//
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf2 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4 ]))
// Broken overlong sequences.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x80, 0x80 ]))
// Ill-formed 4-byte sequences.
// 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+14yyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf5 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf6 ]))
// U+1Cyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf7 ]))
// Ill-formed 5-byte sequences.
// 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+20yyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0x88 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf9, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfa, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfb, 0x80 ]))
// U+3FCyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfb, 0xbf ]))
// Ill-formed 6-byte sequences.
// 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+400yyxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x84, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0x80, 0x80 ]))
// U+7FFCyyxx (invalid)
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xfd, 0xbf, 0xbf ]))
//
// Sequences with four continuation bytes missing
//
// Ill-formed 5-byte sequences.
// 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+uzyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf8 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf9 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfa ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfb ]))
// U+3zyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfb ]))
// Broken overlong sequences.
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf8 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0x80 ]))
// Ill-formed 6-byte sequences.
// 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+uzzyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0x84 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfd, 0x80 ]))
// U+7Fzzyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfd, 0xbf ]))
//
// Sequences with five continuation bytes missing
//
// Ill-formed 6-byte sequences.
// 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx
// U+uzzyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfc ]))
// U+uuzzyyxx (invalid)
expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfd ]))
//
// Consecutive sequences with trailing bytes missing
//
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, /**/ 0xfffd, 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, /**/ 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd,
0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xc0, /**/ 0xe0, 0x80, /**/ 0xf0, 0x80, 0x80,
0xf8, 0x80, 0x80, 0x80,
0xfc, 0x80, 0x80, 0x80, 0x80,
0xdf, /**/ 0xef, 0xbf, /**/ 0xf7, 0xbf, 0xbf,
0xfb, 0xbf, 0xbf, 0xbf,
0xfd, 0xbf, 0xbf, 0xbf, 0xbf ]))
}
UTF8Decoder.test("OverlongSequences") {
//
// Overlong UTF-8 sequences
//
// U+002F SOLIDUS
expectTrue(checkDecodeUTF8([ 0x002f ], [], [ 0x2f ]))
// Overlong sequences of the above.
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0xaf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xe0, 0x80, 0xaf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x80, 0x80, 0xaf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x80, 0x80, 0x80, 0xaf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x80, 0x80, 0x80, 0x80, 0xaf ]))
// U+0000 NULL
expectTrue(checkDecodeUTF8([ 0x0000 ], [], [ 0x00 ]))
// Overlong sequences of the above.
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xe0, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x80, 0x80, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x80, 0x80, 0x80, 0x80, 0x80 ]))
// Other overlong and ill-formed sequences.
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0xbf ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc1, 0x80 ]))
expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc1, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xe0, 0x9f, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xa0, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x8f, 0x80, 0x80 ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf0, 0x8f, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xf8, 0x87, 0xbf, 0xbf, 0xbf ]))
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xfc, 0x83, 0xbf, 0xbf, 0xbf, 0xbf ]))
}
UTF8Decoder.test("IsolatedSurrogates") {
// Unicode 6.3.0:
//
// D71. High-surrogate code point: A Unicode code point in the range
// U+D800 to U+DBFF.
//
// D73. Low-surrogate code point: A Unicode code point in the range
// U+DC00 to U+DFFF.
// Note: U+E0100 is <DB40 DD00> in UTF-16.
// High-surrogates
// U+D800
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xa0, 0x80 ]))
expectTrue(checkDecodeUTF8(
[ 0x0041 ],
[ 0xfffd, 0xfffd, 0xfffd, 0x0041 ],
[ 0x41, 0xed, 0xa0, 0x80, 0x41 ]))
// U+DB40
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xac, 0xa0 ]))
// U+DBFF
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xaf, 0xbf ]))
// Low-surrogates
// U+DC00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xb0, 0x80 ]))
// U+DD00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xb4, 0x80 ]))
// U+DFFF
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xbf, 0xbf ]))
}
UTF8Decoder.test("SurrogatePairs") {
// Surrogate pairs
// U+D800 U+DC00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80 ]))
// U+D800 U+DD00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xa0, 0x80, 0xed, 0xb4, 0x80 ]))
// U+D800 U+DFFF
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf ]))
// U+DB40 U+DC00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xac, 0xa0, 0xed, 0xb0, 0x80 ]))
// U+DB40 U+DD00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xac, 0xa0, 0xed, 0xb4, 0x80 ]))
// U+DB40 U+DFFF
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xac, 0xa0, 0xed, 0xbf, 0xbf ]))
// U+DBFF U+DC00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80 ]))
// U+DBFF U+DD00
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xaf, 0xbf, 0xed, 0xb4, 0x80 ]))
// U+DBFF U+DFFF
expectTrue(checkDecodeUTF8(
[],
[ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ],
[ 0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf ]))
}
UTF8Decoder.test("Noncharacters") {
//
// Noncharacters
//
// Unicode 6.3.0:
//
// D14. Noncharacter: A code point that is permanently reserved for
// internal use and that should never be interchanged. Noncharacters
// consist of the values U+nFFFE and U+nFFFF (where n is from 0 to 1016)
// and the values U+FDD0..U+FDEF.
// U+FFFE
expectTrue(checkDecodeUTF8([ 0xfffe ], [], [ 0xef, 0xbf, 0xbe ]))
// U+FFFF
expectTrue(checkDecodeUTF8([ 0xffff ], [], [ 0xef, 0xbf, 0xbf ]))
// U+1FFFE
expectTrue(checkDecodeUTF8([ 0x1fffe ], [], [ 0xf0, 0x9f, 0xbf, 0xbe ]))
// U+1FFFF
expectTrue(checkDecodeUTF8([ 0x1ffff ], [], [ 0xf0, 0x9f, 0xbf, 0xbf ]))
// U+2FFFE
expectTrue(checkDecodeUTF8([ 0x2fffe ], [], [ 0xf0, 0xaf, 0xbf, 0xbe ]))
// U+2FFFF
expectTrue(checkDecodeUTF8([ 0x2ffff ], [], [ 0xf0, 0xaf, 0xbf, 0xbf ]))
// U+3FFFE
expectTrue(checkDecodeUTF8([ 0x3fffe ], [], [ 0xf0, 0xbf, 0xbf, 0xbe ]))
// U+3FFFF
expectTrue(checkDecodeUTF8([ 0x3ffff ], [], [ 0xf0, 0xbf, 0xbf, 0xbf ]))
// U+4FFFE
expectTrue(checkDecodeUTF8([ 0x4fffe ], [], [ 0xf1, 0x8f, 0xbf, 0xbe ]))
// U+4FFFF
expectTrue(checkDecodeUTF8([ 0x4ffff ], [], [ 0xf1, 0x8f, 0xbf, 0xbf ]))
// U+5FFFE
expectTrue(checkDecodeUTF8([ 0x5fffe ], [], [ 0xf1, 0x9f, 0xbf, 0xbe ]))
// U+5FFFF
expectTrue(checkDecodeUTF8([ 0x5ffff ], [], [ 0xf1, 0x9f, 0xbf, 0xbf ]))
// U+6FFFE
expectTrue(checkDecodeUTF8([ 0x6fffe ], [], [ 0xf1, 0xaf, 0xbf, 0xbe ]))
// U+6FFFF
expectTrue(checkDecodeUTF8([ 0x6ffff ], [], [ 0xf1, 0xaf, 0xbf, 0xbf ]))
// U+7FFFE
expectTrue(checkDecodeUTF8([ 0x7fffe ], [], [ 0xf1, 0xbf, 0xbf, 0xbe ]))
// U+7FFFF
expectTrue(checkDecodeUTF8([ 0x7ffff ], [], [ 0xf1, 0xbf, 0xbf, 0xbf ]))
// U+8FFFE
expectTrue(checkDecodeUTF8([ 0x8fffe ], [], [ 0xf2, 0x8f, 0xbf, 0xbe ]))
// U+8FFFF
expectTrue(checkDecodeUTF8([ 0x8ffff ], [], [ 0xf2, 0x8f, 0xbf, 0xbf ]))
// U+9FFFE
expectTrue(checkDecodeUTF8([ 0x9fffe ], [], [ 0xf2, 0x9f, 0xbf, 0xbe ]))
// U+9FFFF
expectTrue(checkDecodeUTF8([ 0x9ffff ], [], [ 0xf2, 0x9f, 0xbf, 0xbf ]))
// U+AFFFE
expectTrue(checkDecodeUTF8([ 0xafffe ], [], [ 0xf2, 0xaf, 0xbf, 0xbe ]))
// U+AFFFF
expectTrue(checkDecodeUTF8([ 0xaffff ], [], [ 0xf2, 0xaf, 0xbf, 0xbf ]))
// U+BFFFE
expectTrue(checkDecodeUTF8([ 0xbfffe ], [], [ 0xf2, 0xbf, 0xbf, 0xbe ]))
// U+BFFFF
expectTrue(checkDecodeUTF8([ 0xbffff ], [], [ 0xf2, 0xbf, 0xbf, 0xbf ]))
// U+CFFFE
expectTrue(checkDecodeUTF8([ 0xcfffe ], [], [ 0xf3, 0x8f, 0xbf, 0xbe ]))
// U+CFFFF
expectTrue(checkDecodeUTF8([ 0xcfffF ], [], [ 0xf3, 0x8f, 0xbf, 0xbf ]))
// U+DFFFE
expectTrue(checkDecodeUTF8([ 0xdfffe ], [], [ 0xf3, 0x9f, 0xbf, 0xbe ]))
// U+DFFFF
expectTrue(checkDecodeUTF8([ 0xdffff ], [], [ 0xf3, 0x9f, 0xbf, 0xbf ]))
// U+EFFFE
expectTrue(checkDecodeUTF8([ 0xefffe ], [], [ 0xf3, 0xaf, 0xbf, 0xbe ]))
// U+EFFFF
expectTrue(checkDecodeUTF8([ 0xeffff ], [], [ 0xf3, 0xaf, 0xbf, 0xbf ]))
// U+FFFFE
expectTrue(checkDecodeUTF8([ 0xffffe ], [], [ 0xf3, 0xbf, 0xbf, 0xbe ]))
// U+FFFFF
expectTrue(checkDecodeUTF8([ 0xfffff ], [], [ 0xf3, 0xbf, 0xbf, 0xbf ]))
// U+10FFFE
expectTrue(checkDecodeUTF8([ 0x10fffe ], [], [ 0xf4, 0x8f, 0xbf, 0xbe ]))
// U+10FFFF
expectTrue(checkDecodeUTF8([ 0x10ffff ], [], [ 0xf4, 0x8f, 0xbf, 0xbf ]))
// U+FDD0
expectTrue(checkDecodeUTF8([ 0xfdd0 ], [], [ 0xef, 0xb7, 0x90 ]))
// U+FDD1
expectTrue(checkDecodeUTF8([ 0xfdd1 ], [], [ 0xef, 0xb7, 0x91 ]))
// U+FDD2
expectTrue(checkDecodeUTF8([ 0xfdd2 ], [], [ 0xef, 0xb7, 0x92 ]))
// U+FDD3
expectTrue(checkDecodeUTF8([ 0xfdd3 ], [], [ 0xef, 0xb7, 0x93 ]))
// U+FDD4
expectTrue(checkDecodeUTF8([ 0xfdd4 ], [], [ 0xef, 0xb7, 0x94 ]))
// U+FDD5
expectTrue(checkDecodeUTF8([ 0xfdd5 ], [], [ 0xef, 0xb7, 0x95 ]))
// U+FDD6
expectTrue(checkDecodeUTF8([ 0xfdd6 ], [], [ 0xef, 0xb7, 0x96 ]))
// U+FDD7
expectTrue(checkDecodeUTF8([ 0xfdd7 ], [], [ 0xef, 0xb7, 0x97 ]))
// U+FDD8
expectTrue(checkDecodeUTF8([ 0xfdd8 ], [], [ 0xef, 0xb7, 0x98 ]))
// U+FDD9
expectTrue(checkDecodeUTF8([ 0xfdd9 ], [], [ 0xef, 0xb7, 0x99 ]))
// U+FDDA
expectTrue(checkDecodeUTF8([ 0xfdda ], [], [ 0xef, 0xb7, 0x9a ]))
// U+FDDB
expectTrue(checkDecodeUTF8([ 0xfddb ], [], [ 0xef, 0xb7, 0x9b ]))
// U+FDDC
expectTrue(checkDecodeUTF8([ 0xfddc ], [], [ 0xef, 0xb7, 0x9c ]))
// U+FDDD
expectTrue(checkDecodeUTF8([ 0xfddd ], [], [ 0xef, 0xb7, 0x9d ]))
// U+FDDE
expectTrue(checkDecodeUTF8([ 0xfdde ], [], [ 0xef, 0xb7, 0x9e ]))
// U+FDDF
expectTrue(checkDecodeUTF8([ 0xfddf ], [], [ 0xef, 0xb7, 0x9f ]))
// U+FDE0
expectTrue(checkDecodeUTF8([ 0xfde0 ], [], [ 0xef, 0xb7, 0xa0 ]))
// U+FDE1
expectTrue(checkDecodeUTF8([ 0xfde1 ], [], [ 0xef, 0xb7, 0xa1 ]))
// U+FDE2
expectTrue(checkDecodeUTF8([ 0xfde2 ], [], [ 0xef, 0xb7, 0xa2 ]))
// U+FDE3
expectTrue(checkDecodeUTF8([ 0xfde3 ], [], [ 0xef, 0xb7, 0xa3 ]))
// U+FDE4
expectTrue(checkDecodeUTF8([ 0xfde4 ], [], [ 0xef, 0xb7, 0xa4 ]))
// U+FDE5
expectTrue(checkDecodeUTF8([ 0xfde5 ], [], [ 0xef, 0xb7, 0xa5 ]))
// U+FDE6
expectTrue(checkDecodeUTF8([ 0xfde6 ], [], [ 0xef, 0xb7, 0xa6 ]))
// U+FDE7
expectTrue(checkDecodeUTF8([ 0xfde7 ], [], [ 0xef, 0xb7, 0xa7 ]))
// U+FDE8
expectTrue(checkDecodeUTF8([ 0xfde8 ], [], [ 0xef, 0xb7, 0xa8 ]))
// U+FDE9
expectTrue(checkDecodeUTF8([ 0xfde9 ], [], [ 0xef, 0xb7, 0xa9 ]))
// U+FDEA
expectTrue(checkDecodeUTF8([ 0xfdea ], [], [ 0xef, 0xb7, 0xaa ]))
// U+FDEB
expectTrue(checkDecodeUTF8([ 0xfdeb ], [], [ 0xef, 0xb7, 0xab ]))
// U+FDEC
expectTrue(checkDecodeUTF8([ 0xfdec ], [], [ 0xef, 0xb7, 0xac ]))
// U+FDED
expectTrue(checkDecodeUTF8([ 0xfded ], [], [ 0xef, 0xb7, 0xad ]))
// U+FDEE
expectTrue(checkDecodeUTF8([ 0xfdee ], [], [ 0xef, 0xb7, 0xae ]))
// U+FDEF
expectTrue(checkDecodeUTF8([ 0xfdef ], [], [ 0xef, 0xb7, 0xaf ]))
// U+FDF0
expectTrue(checkDecodeUTF8([ 0xfdf0 ], [], [ 0xef, 0xb7, 0xb0 ]))
// U+FDF1
expectTrue(checkDecodeUTF8([ 0xfdf1 ], [], [ 0xef, 0xb7, 0xb1 ]))
// U+FDF2
expectTrue(checkDecodeUTF8([ 0xfdf2 ], [], [ 0xef, 0xb7, 0xb2 ]))
// U+FDF3
expectTrue(checkDecodeUTF8([ 0xfdf3 ], [], [ 0xef, 0xb7, 0xb3 ]))
// U+FDF4
expectTrue(checkDecodeUTF8([ 0xfdf4 ], [], [ 0xef, 0xb7, 0xb4 ]))
// U+FDF5
expectTrue(checkDecodeUTF8([ 0xfdf5 ], [], [ 0xef, 0xb7, 0xb5 ]))
// U+FDF6
expectTrue(checkDecodeUTF8([ 0xfdf6 ], [], [ 0xef, 0xb7, 0xb6 ]))
// U+FDF7
expectTrue(checkDecodeUTF8([ 0xfdf7 ], [], [ 0xef, 0xb7, 0xb7 ]))
// U+FDF8
expectTrue(checkDecodeUTF8([ 0xfdf8 ], [], [ 0xef, 0xb7, 0xb8 ]))
// U+FDF9
expectTrue(checkDecodeUTF8([ 0xfdf9 ], [], [ 0xef, 0xb7, 0xb9 ]))
// U+FDFA
expectTrue(checkDecodeUTF8([ 0xfdfa ], [], [ 0xef, 0xb7, 0xba ]))
// U+FDFB
expectTrue(checkDecodeUTF8([ 0xfdfb ], [], [ 0xef, 0xb7, 0xbb ]))
// U+FDFC
expectTrue(checkDecodeUTF8([ 0xfdfc ], [], [ 0xef, 0xb7, 0xbc ]))
// U+FDFD
expectTrue(checkDecodeUTF8([ 0xfdfd ], [], [ 0xef, 0xb7, 0xbd ]))
// U+FDFE
expectTrue(checkDecodeUTF8([ 0xfdfe ], [], [ 0xef, 0xb7, 0xbe ]))
// U+FDFF
expectTrue(checkDecodeUTF8([ 0xfdff ], [], [ 0xef, 0xb7, 0xbf ]))
}
var UTF16Decoder = TestSuite("UTF16Decoder")
UTF16Decoder.test("UTF16.transcodedLength") {
do {
let u8: [Unicode.UTF8.CodeUnit] = [ 0, 1, 2, 3, 4, 5 ]
let (count, isASCII) = Unicode.UTF16.transcodedLength(
of: u8.makeIterator(),
decodedAs: Unicode.UTF8.self,
repairingIllFormedSequences: false)!
expectEqual(6, count)
expectTrue(isASCII)
}
do {
// "€" == U+20AC.
let u8: [Unicode.UTF8.CodeUnit] = [ 0xF0, 0xA4, 0xAD, 0xA2 ]
let (count, isASCII) = Unicode.UTF16.transcodedLength(
of: u8.makeIterator(),
decodedAs: Unicode.UTF8.self,
repairingIllFormedSequences: false)!
expectEqual(2, count)
expectFalse(isASCII)
}
do {
let u16: [Unicode.UTF16.CodeUnit] = [ 6, 7, 8, 9, 10, 11 ]
let (count, isASCII) = Unicode.UTF16.transcodedLength(
of: u16.makeIterator(),
decodedAs: Unicode.UTF16.self,
repairingIllFormedSequences: false)!
expectEqual(6, count)
expectTrue(isASCII)
}
}
UTF16Decoder.test("Decoding1").forEach(in: utfTests) {
test in
expectTrue(
checkDecodeUTF16(
test.utf32, test.utf32RepairedTail, test.utf16),
stackTrace: test.loc.withCurrentLoc())
return ()
}
UTF16Decoder.test("Decoding2") {
for (name, batch) in utf16Tests {
print("Batch: \(name)")
for test in batch {
expectTrue(checkDecodeUTF16(test.scalarsHead, test.scalarsRepairedTail,
test.encoded), stackTrace: test.loc.withCurrentLoc())
}
}
}
public struct UTF16Test {
public let scalarsHead: [UInt32]
public let scalarsRepairedTail: [UInt32]
public let encoded: [UInt16]
public let loc: SourceLoc
public init(
_ scalarsHead: [UInt32], _ scalarsRepairedTail: [UInt32],
_ encoded: [UInt16],
file: String = #file, line: UInt = #line
) {
self.scalarsHead = scalarsHead
self.scalarsRepairedTail = scalarsRepairedTail
self.encoded = encoded
self.loc = SourceLoc(file, line, comment: "test data")
}
}
public let utf16Tests = [
"Incomplete": [
//
// Incomplete sequences that end right before EOF.
//
// U+D800 (high-surrogate)
UTF16Test([], [ 0xFFFD ], [ 0xD800 ]),
// U+D800 (high-surrogate)
// U+D800 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xD800, 0xD800 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
UTF16Test([ 0x0041 ], [ 0xFFFD ], [ 0x0041, 0xD800 ]),
// U+10000 LINEAR B SYLLABLE B008 A
// U+D800 (high-surrogate)
UTF16Test(
[ 0x0001_0000 ], [ 0xFFFD ],
[ 0xD800, 0xDC00, 0xD800 ]),
//
// Incomplete sequences with more code units following them.
//
// U+D800 (high-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test([], [ 0xFFFD, 0x0041 ], [ 0xD800, 0x0041 ]),
// U+D800 (high-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[], [ 0xFFFD, 0x0001_0000 ],
[ 0xD800, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0x0041 ],
[ 0x0041, 0xD800, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xD800, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+DB40 (high-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0041 ],
[ 0x0041, 0xD800, 0xDB40, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+DB40 (high-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xD800, 0xDB40, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+DB40 (high-surrogate)
// U+DBFF (high-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0041 ],
[ 0x0041, 0xD800, 0xDB40, 0xDBFF, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+D800 (high-surrogate)
// U+DB40 (high-surrogate)
// U+DBFF (high-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xD800, 0xDB40, 0xDBFF, 0xD800, 0xDC00 ]),
],
"IllFormed": [
//
// Low-surrogate right before EOF.
//
// U+DC00 (low-surrogate)
UTF16Test([], [ 0xFFFD ], [ 0xDC00 ]),
// U+DC00 (low-surrogate)
// U+DC00 (low-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
UTF16Test([ 0x0041 ], [ 0xFFFD ], [ 0x0041, 0xDC00 ]),
// U+10000 LINEAR B SYLLABLE B008 A
// U+DC00 (low-surrogate)
UTF16Test(
[ 0x0001_0000 ], [ 0xFFFD ],
[ 0xD800, 0xDC00, 0xDC00 ]),
//
// Low-surrogate with more code units following it.
//
// U+DC00 (low-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test([], [ 0xFFFD, 0x0041 ], [ 0xDC00, 0x0041 ]),
// U+DC00 (low-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[], [ 0xFFFD, 0x0001_0000 ],
[ 0xDC00, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0x0041 ],
[ 0x0041, 0xDC00, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xDC00, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+DD00 (low-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0041 ],
[ 0x0041, 0xDC00, 0xDD00, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+DD00 (low-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xDC00, 0xDD00, 0xD800, 0xDC00 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+DD00 (low-surrogate)
// U+DFFF (low-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0041 ],
[ 0x0041, 0xDC00, 0xDD00, 0xDFFF, 0x0041 ]),
// U+0041 LATIN CAPITAL LETTER A
// U+DC00 (low-surrogate)
// U+DD00 (low-surrogate)
// U+DFFF (low-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0001_0000 ],
[ 0x0041, 0xDC00, 0xDD00, 0xDFFF, 0xD800, 0xDC00 ]),
//
// Low-surrogate followed by high-surrogate.
//
// U+DC00 (low-surrogate)
// U+D800 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xD800 ]),
// U+DC00 (low-surrogate)
// U+DB40 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDB40 ]),
// U+DC00 (low-surrogate)
// U+DBFF (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDBFF ]),
// U+DD00 (low-surrogate)
// U+D800 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xD800 ]),
// U+DD00 (low-surrogate)
// U+DB40 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xDB40 ]),
// U+DD00 (low-surrogate)
// U+DBFF (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xDBFF ]),
// U+DFFF (low-surrogate)
// U+D800 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xD800 ]),
// U+DFFF (low-surrogate)
// U+DB40 (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xDB40 ]),
// U+DFFF (low-surrogate)
// U+DBFF (high-surrogate)
UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xDBFF ]),
// U+DC00 (low-surrogate)
// U+D800 (high-surrogate)
// U+0041 LATIN CAPITAL LETTER A
UTF16Test(
[], [ 0xFFFD, 0xFFFD, 0x0041 ],
[ 0xDC00, 0xD800, 0x0041 ]),
// U+DC00 (low-surrogate)
// U+D800 (high-surrogate)
// U+10000 LINEAR B SYLLABLE B008 A
UTF16Test(
[], [ 0xFFFD, 0xFFFD, 0x10000 ],
[ 0xDC00, 0xD800, 0xD800, 0xDC00 ]),
],
]
runAllTests()
#else
//===--- benchmarking -----------------------------------------------------===//
@inline(never)
public func run_UTF8Decode(_ N: Int) {
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
// 2-byte sequences
let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."
// 3-byte sequences
let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"
// 4-byte sequences
// Most commonly emoji, which are usually mixed with other text.
let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."
let strings = [ascii, russian, japanese, emoji].map { Array($0.utf8) }
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true
default:
return false
}
}
var total: UInt32 = 0
for _ in 1...200*N {
for string in strings {
#if BASELINE
_ = transcode(
string.makeIterator(), from: Unicode.UTF8.self, to: Unicode.UTF32.self,
stoppingOnError: false
) {
total = total &+ $0
}
#else
#if FORWARD
var it = string.makeIterator()
typealias D = Unicode.UTF8.ForwardParser
D.decode(&it, repairingIllFormedSequences: true) { total = total &+ $0.value }
#elseif REVERSE
var it = string.reversed().makeIterator()
typealias D = Unicode.UTF8.ReverseParser
D.decode(&it, repairingIllFormedSequences: true) { total = total &+ $0.value }
#elseif SEQUENCE
for s in Unicode.DefaultScalarView(string, fromEncoding: Unicode.UTF8.self) {
total = total &+ s.value
}
#elseif COLLECTION
let scalars = Unicode.DefaultScalarView(string, fromEncoding: Unicode.UTF8.self)
var i = scalars.startIndex
while i != scalars.endIndex {
total = total &+ scalars[i].value
i = scalars.index(after: i)
}
#elseif REVERSE_COLLECTION
let scalars = Unicode.DefaultScalarView(string, fromEncoding: Unicode.UTF8.self)
var i = scalars.endIndex
while i != scalars.startIndex {
i = scalars.index(before: i)
total = total &+ scalars[i].value
}
#else
Error_Unknown_Benchmark()
#endif
#endif
}
}
if CommandLine.arguments.count > 1000 { print(total) }
}
run_UTF8Decode(10000)
#endif
| 30.591754 | 591 | 0.615612 |
7178eda1b6499570527962fd3af814a90dfa10e7 | 721 | //
// TestModel.swift
// FRCDemo
//
// Created by Evgeny Velichko on 09.06.2020.
// Copyright © 2020 Evgeny Velichko. All rights reserved.
//
import Foundation
import CoreData
struct TestModel {
let id: String
let text: String
}
// MARK: - EntityConvertable
extension CDTestModel: EntityConvertable {
func toEntity() -> TestModel {
.init(id: id ?? "",
text: text ?? "")
}
}
// MARK: - ManagedObjectConvertible
extension TestModel: ManagedObjectConvertible {
func toManagedObject(in context: NSManagedObjectContext) -> CDTestModel {
with(CDTestModel.firstOrCreate(context: context, id: id)) {
$0.id = id
$0.text = text
}
}
}
| 19.486486 | 77 | 0.628294 |
e0178ef11e608e00eb0bc9d3337d4eac006f54ca | 2,765 | //
// CardsNavigationContainer.swift
// mCardsContainer
//
// Created by Alex Hmelevski on 2019-11-12.
//
import Foundation
import AHContainer
final class CardsNavigationContainer: UIViewController, VCContainer {
let cardsContainer: CardsContainer
let collectionViewControllerWrapper: VCContainer
init(config: CardsContainerConfig) {
let collectionView = CardsCollectionViewContainer(cardsContainer: config.collectionViewController)
collectionViewControllerWrapper = collectionView
let newConfig = CardsContainerConfig(source: config.source,
collectionViewController: collectionView,
animationProvider: config.animationProvider,
buttomView: config.bottomView,
buttomViewHeightProportion: config.bottomViewHeightProportion)
cardsContainer = CardsContainer(config: newConfig)
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
addChild(cardsContainer)
view.addSubview(cardsContainer.view)
cardsContainer.view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: cardsContainer.view.safeAreaLayoutGuide.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: cardsContainer.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
view.leftAnchor.constraint(equalTo: cardsContainer.view.safeAreaLayoutGuide.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: cardsContainer.view.safeAreaLayoutGuide.rightAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(_ vc: UIViewController, using provider: TransitionProvider, completion: ((Bool) -> Void)?) {
collectionViewControllerWrapper.show(vc, using: provider, completion: completion)
}
func push(controller vc: UIViewController, with provider: TransitionProvider, completion: ((Bool) -> Void)?) {
collectionViewControllerWrapper.push(controller: vc, with: provider, completion: completion)
}
func pop(using provider: AnimationTransitionProvider, completion: ((Bool) -> Void)?) -> UIViewController? {
return collectionViewControllerWrapper.pop(using: provider, completion: completion)
}
func pop(to vc: UIViewController, using provider: AnimationTransitionProvider, completion: ((Bool) -> Void)?) -> [UIViewController] {
return collectionViewControllerWrapper.pop(to: vc, using: provider, completion: completion)
}
}
| 45.327869 | 137 | 0.694033 |
90c8202bacf6f4dc86e35ea47cf98c1df495064c | 540 | import Foundation
#if os(iOS)
import UIKit
#endif
public struct Position {
public let x: Float
public let y: Float
public let z: Float?
public init(_ x: Float, _ y: Float, _ z: Float? = nil) {
self.x = x
self.y = y
self.z = z
}
#if !os(Linux)
public init(point: CGPoint) {
x = Float(point.x)
y = Float(point.y)
z = nil
}
#endif
public static let center = Position(0.5, 0.5)
public static let zero = Position(0.0, 0.0)
} | 19.285714 | 60 | 0.525926 |
d9d507ef16c0507a87feb5697ceaae59d77d08bd | 129,343 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
@inlinable // This is @inlinable as trivially computable.
private func malloc_good_size(_ size: Int) -> Int {
return size
}
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
munmap(mem, length)
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
@_implementationOnly import _SwiftFoundationOverlayShims
@_implementationOnly import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
@_alwaysEmitIntoClient
internal func _withStackOrHeapBuffer(capacity: Int, _ body: (UnsafeMutableBufferPointer<UInt8>) -> Void) {
guard capacity > 0 else {
body(UnsafeMutableBufferPointer(start: nil, count: 0))
return
}
typealias InlineBuffer = ( // 32 bytes
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
)
let inlineCount = MemoryLayout<InlineBuffer>.size
if capacity <= inlineCount {
var buffer: InlineBuffer = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
withUnsafeMutableBytes(of: &buffer) { buffer in
assert(buffer.count == inlineCount)
let start = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
body(UnsafeMutableBufferPointer(start: start, count: capacity))
}
return
}
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: capacity)
defer { buffer.deallocate() }
body(buffer)
}
// Underlying storage representation for medium and large data.
// Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial.
// NOTE: older overlays called this class _DataStorage. The two must
// coexist without a conflicting ObjC class name, so it was renamed.
// The old name must not be used in the new runtime.
@usableFromInline
internal final class __DataStorage {
@usableFromInline static let maxSize = Int.max >> 1
@usableFromInline static let vmOpsThreshold = NSPageSize() * 4
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
@usableFromInline var _bytes: UnsafeMutableRawPointer?
@usableFromInline var _length: Int
@usableFromInline var _capacity: Int
@usableFromInline var _offset: Int
@usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
@usableFromInline var _needToZero: Bool
@inlinable // This is @inlinable as trivially computable.
var bytes: UnsafeRawPointer? {
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable as trivially computable.
var mutableBytes: UnsafeMutableRawPointer? {
return _bytes?.advanced(by: -_offset)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return _capacity
}
@inlinable // This is @inlinable as trivially computable.
var length: Int {
get {
return _length
}
set {
setLength(newValue)
}
}
@inlinable // This is inlinable as trivially computable.
var isExternallyOwned: Bool {
// all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation
// anything with 0 capacity means that we have not allocated this pointer and consequently mutation is not ours to make.
return _capacity == 0
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) {
guard isExternallyOwned || newLength > _capacity else { return }
if newLength == 0 {
if isExternallyOwned {
let newCapacity = malloc_good_size(_length)
let newBytes = __DataStorage.allocate(newCapacity, false)
__DataStorage.move(newBytes!, _bytes!, _length)
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_needToZero = false
}
} else if isExternallyOwned {
let newCapacity = malloc_good_size(newLength)
let newBytes = __DataStorage.allocate(newCapacity, clear)
if let bytes = _bytes {
__DataStorage.move(newBytes!, bytes, _length)
}
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_length = newLength
_needToZero = true
} else {
let cap = _capacity
var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity))
let origLength = _length
var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = __DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength)
newBytes = __DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = malloc_good_size(newLength)
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
_deallocator = nil
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv)
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func setLength(_ length: Int) {
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
__DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func get(_ index: Int) -> UInt8 {
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func set(_ index: Int, to value: UInt8) {
ensureUniqueBufferReference()
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))
UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer)
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
let shift = resultingLength - currentLength
let mutableBytes: UnsafeMutableRawPointer
if resultingLength > currentLength {
ensureUniqueBufferReference(growingTo: resultingLength)
_length = resultingLength
} else {
ensureUniqueBufferReference()
}
mutableBytes = _bytes!
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func resetBytes(in range_: Range<Int>) {
let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound)
if range.length == 0 { return }
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity <= newLength {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
} else {
ensureUniqueBufferReference()
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
}
@usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer.
init(length: Int) {
precondition(length < __DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = __DataStorage.shouldAllocateCleared(length)
_bytes = __DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(capacity capacity_: Int = 0) {
var capacity = capacity_
precondition(capacity < __DataStorage.maxSize)
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < __DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
}
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < __DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_deallocator = { _, _ in
_fixLifetime(immutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_deallocator = { _, _ in
_fixLifetime(mutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: customReference.bytes)
_capacity = 0
_needToZero = false
_length = customReference.length
_deallocator = { _, _ in
_fixLifetime(customReference)
}
}
@usableFromInline // This is not @inlinable as a non-convience initializer.
init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = customMutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = customMutableReference.length
_deallocator = { _, _ in
_fixLifetime(customMutableReference)
}
}
deinit {
_freeBytes()
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func mutableCopy(_ range: Range<Int>) -> __DataStorage {
return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed.
func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false))
}
@inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients.
@usableFromInline
func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
return __NSSwiftData(backing: self, range: range)
}
}
// NOTE: older overlays called this _NSSwiftData. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
internal class __NSSwiftData : NSData {
var _backing: __DataStorage!
var _range: Range<Data.Index>!
convenience init(backing: __DataStorage, range: Range<Data.Index>) {
self.init()
_backing = backing
_range = range
}
@objc override var length: Int {
return _range.upperBound - _range.lowerBound
}
@objc override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
@objc override func copy(with zone: NSZone? = nil) -> Any {
return self
}
@objc override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
@frozen
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
// A small inline buffer of bytes suitable for stack-allocation of small data.
// Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible.
@usableFromInline
@frozen
internal struct InlineData {
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#elseif arch(i386) || arch(arm)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#endif
@usableFromInline var length: UInt8
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count <= MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ srcBuffer: UnsafeRawBufferPointer) {
self.init(count: srcBuffer.count)
if !srcBuffer.isEmpty {
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count)
}
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(count: Int = 0) {
assert(count <= MemoryLayout<Buffer>.size)
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#elseif arch(i386) || arch(arm)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#endif
length = UInt8(count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: InlineSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: LargeSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(length)
}
set(newValue) {
assert(newValue <= MemoryLayout<Buffer>.size)
length = UInt8(newValue)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return 0
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return count
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as tribially computable.
mutating func append(byte: UInt8) {
let count = self.count
assert(count + 1 <= MemoryLayout<Buffer>.size)
Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte }
self.length += 1
}
@inlinable // This is @inlinable as trivially computable.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
guard !buffer.isEmpty else { return }
assert(count + buffer.count <= MemoryLayout<Buffer>.size)
let cnt = count
_ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count)
}
length += UInt8(buffer.count)
}
@inlinable // This is @inlinable as trivially computable.
subscript(index: Index) -> UInt8 {
get {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in
return rawBuffer[index]
}
}
set(newValue) {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer[index] = newValue
}
}
}
@inlinable // This is @inlinable as trivially computable.
mutating func resetBytes(in range: Range<Index>) {
assert(range.lowerBound <= MemoryLayout<Buffer>.size)
assert(range.upperBound <= MemoryLayout<Buffer>.size)
precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)")
if count < range.upperBound {
count = range.upperBound
}
let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
memset(rawBuffer.baseAddress?.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) {
assert(subrange.lowerBound <= MemoryLayout<Buffer>.size)
assert(subrange.upperBound <= MemoryLayout<Buffer>.size)
assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size)
precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)")
precondition(subrange.upperBound <= length, "index \(subrange.upperBound) is out of bounds of 0..<\(length)")
let currentLength = count
let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength
let shift = resultingLength - currentLength
Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in
/* shift the trailing bytes */
let start = subrange.lowerBound
let length = subrange.upperBound - subrange.lowerBound
if shift != 0 {
memmove(mutableBytes.baseAddress?.advanced(by: start + replacementLength), mutableBytes.baseAddress?.advanced(by: start + length), currentLength - start - length)
}
if replacementLength != 0 {
memmove(mutableBytes.baseAddress?.advanced(by: start), replacementBytes!, replacementLength)
}
}
count = resultingLength
}
@inlinable // This is @inlinable as trivially computable.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
Swift.withUnsafeBytes(of: bytes) {
let cnt = Swift.min($0.count, range.upperBound - range.lowerBound)
guard cnt > 0 else { return }
pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt)
}
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
// **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8)
// Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash.
//
// This affects slices, which are InlineSlice and not InlineData:
//
// let d = Data([0xFF, 0xFF]) // InlineData
// let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice
// assert(s == d)
// assert(s.hashValue == d.hashValue)
hasher.combine(count)
Swift.withUnsafeBytes(of: bytes) {
// We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage).
let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count)
hasher.combine(bytes: bytes)
}
}
}
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline internal typealias HalfInt = Int32
#elseif arch(i386) || arch(arm)
@usableFromInline internal typealias HalfInt = Int16
#endif
// A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words.
// Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
@usableFromInline
@frozen
internal struct InlineSlice {
// ***WARNING***
// These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
@usableFromInline var slice: Range<HalfInt>
@usableFromInline var storage: __DataStorage
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count < HalfInt.max
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ buffer: UnsafeRawBufferPointer) {
assert(buffer.count < HalfInt.max)
self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(capacity: Int) {
assert(capacity < HalfInt.max)
self.init(__DataStorage(capacity: capacity), count: 0)
}
@inlinable // This is @inlinable as a convenience initializer.
init(count: Int) {
assert(count < HalfInt.max)
self.init(__DataStorage(length: count), count: count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData) {
assert(inline.count < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice) {
assert(large.range.lowerBound < HalfInt.max)
assert(large.range.upperBound < HalfInt.max)
self.init(large.storage, range: large.range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(large.storage, range: range)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
assert(count < HalfInt.max)
self.storage = storage
slice = 0..<HalfInt(count)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.storage = storage
slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound)
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func ensureUniqueReference() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.mutableCopy(self.range)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return Int(slice.lowerBound)
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return Int(slice.upperBound)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return storage.capacity
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func reserveCapacity(_ minimumCapacity: Int) {
ensureUniqueReference()
// the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(slice.upperBound - slice.lowerBound)
}
set(newValue) {
assert(newValue < HalfInt.max)
ensureUniqueReference()
storage.length = newValue
slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue))
}
}
@inlinable // This is @inlinable as trivially computable.
var range: Range<Int> {
get {
return Int(slice.lowerBound)..<Int(slice.upperBound)
}
set(newValue) {
assert(newValue.lowerBound < HalfInt.max)
assert(newValue.upperBound < HalfInt.max)
slice = HalfInt(newValue.lowerBound)..<HalfInt(newValue.upperBound)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try storage.withUnsafeBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
ensureUniqueReference()
return try storage.withUnsafeMutableBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
assert(endIndex + buffer.count < HalfInt.max)
ensureUniqueReference()
storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count)
slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count)
}
@inlinable // This is @inlinable as reasonably small.
subscript(index: Index) -> UInt8 {
get {
assert(index < HalfInt.max)
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
return storage.get(index)
}
set(newValue) {
assert(index < HalfInt.max)
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.set(index, to: newValue)
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
return storage.bridgedReference(self.range)
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Index>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.resetBytes(in: range)
if slice.upperBound < range.upperBound {
slice = slice.lowerBound..<HalfInt(range.upperBound)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
ensureUniqueReference()
let upper = range.upperBound
storage.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
slice = slice.lowerBound..<HalfInt(resultingUpper)
}
@inlinable // This is @inlinable as reasonably small.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
storage.copyBytes(to: pointer, from: range)
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
hasher.combine(count)
// At most, hash the first 80 bytes of this data.
let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
storage.withUnsafeBytes(in: range) {
hasher.combine(bytes: $0)
}
}
}
// A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word.
// Inlinability strategy: everything should be inlinable as trivial.
@usableFromInline
@_fixed_layout
internal final class RangeReference {
@usableFromInline var range: Range<Int>
@inlinable @inline(__always) // This is @inlinable as trivially forwarding.
var lowerBound: Int {
return range.lowerBound
}
@inlinable @inline(__always) // This is @inlinable as trivially forwarding.
var upperBound: Int {
return range.upperBound
}
@inlinable @inline(__always) // This is @inlinable as trivially computable.
var count: Int {
return range.upperBound - range.lowerBound
}
@inlinable @inline(__always) // This is @inlinable as a trivial initializer.
init(_ range: Range<Int>) {
self.range = range
}
}
// A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size.
// Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
@usableFromInline
@frozen
internal struct LargeSlice {
// ***WARNING***
// These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
@usableFromInline var slice: RangeReference
@usableFromInline var storage: __DataStorage
@inlinable // This is @inlinable as a convenience initializer.
init(_ buffer: UnsafeRawBufferPointer) {
self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(capacity: Int) {
self.init(__DataStorage(capacity: capacity), count: 0)
}
@inlinable // This is @inlinable as a convenience initializer.
init(count: Int) {
self.init(__DataStorage(length: count), count: count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData) {
let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }
self.init(storage, count: inline.count)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ slice: InlineSlice) {
self.storage = slice.storage
self.slice = RangeReference(slice.range)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
self.storage = storage
self.slice = RangeReference(0..<count)
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func ensureUniqueReference() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.mutableCopy(range)
}
if !isKnownUniquelyReferenced(&slice) {
slice = RangeReference(range)
}
}
@inlinable // This is @inlinable as trivially forwarding.
var startIndex: Int {
return slice.range.lowerBound
}
@inlinable // This is @inlinable as trivially forwarding.
var endIndex: Int {
return slice.range.upperBound
}
@inlinable // This is @inlinable as trivially forwarding.
var capacity: Int {
return storage.capacity
}
@inlinable // This is @inlinable as trivially computable.
mutating func reserveCapacity(_ minimumCapacity: Int) {
ensureUniqueReference()
// the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return slice.count
}
set(newValue) {
ensureUniqueReference()
storage.length = newValue
slice.range = slice.range.lowerBound..<(slice.range.lowerBound + newValue)
}
}
@inlinable // This is @inlinable as it is trivially forwarding.
var range: Range<Int> {
return slice.range
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try storage.withUnsafeBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
ensureUniqueReference()
return try storage.withUnsafeMutableBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
ensureUniqueReference()
storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count)
slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count
}
@inlinable // This is @inlinable as trivially computable.
subscript(index: Index) -> UInt8 {
get {
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
return storage.get(index)
}
set(newValue) {
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.set(index, to: newValue)
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
return storage.bridgedReference(self.range)
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Int>) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.resetBytes(in: range)
if slice.range.upperBound < range.upperBound {
slice.range = slice.range.lowerBound..<range.upperBound
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
ensureUniqueReference()
let upper = range.upperBound
storage.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
slice.range = slice.range.lowerBound..<resultingUpper
}
@inlinable // This is @inlinable as reasonably small.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
storage.copyBytes(to: pointer, from: range)
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
hasher.combine(count)
// Hash at most the first 80 bytes of this data.
let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
storage.withUnsafeBytes(in: range) {
hasher.combine(bytes: $0)
}
}
}
// The actual storage for Data's various representations.
// Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.)
@usableFromInline
@frozen
internal enum _Representation {
case empty
case inline(InlineData)
case slice(InlineSlice)
case large(LargeSlice)
@inlinable // This is @inlinable as a trivial initializer.
init(_ buffer: UnsafeRawBufferPointer) {
if buffer.isEmpty {
self = .empty
} else if InlineData.canStore(count: buffer.count) {
self = .inline(InlineData(buffer))
} else if InlineSlice.canStore(count: buffer.count) {
self = .slice(InlineSlice(buffer))
} else {
self = .large(LargeSlice(buffer))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) {
if buffer.isEmpty {
self = .empty
} else if InlineData.canStore(count: buffer.count) {
self = .inline(InlineData(buffer))
} else {
let count = buffer.count
let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in
_fixLifetime(owner)
}, offset: 0)
if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(storage, count: count))
} else {
self = .large(LargeSlice(storage, count: count))
}
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(capacity: Int) {
if capacity == 0 {
self = .empty
} else if InlineData.canStore(count: capacity) {
self = .inline(InlineData())
} else if InlineSlice.canStore(count: capacity) {
self = .slice(InlineSlice(capacity: capacity))
} else {
self = .large(LargeSlice(capacity: capacity))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(count: Int) {
if count == 0 {
self = .empty
} else if InlineData.canStore(count: count) {
self = .inline(InlineData(count: count))
} else if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(count: count))
} else {
self = .large(LargeSlice(count: count))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
if count == 0 {
self = .empty
} else if InlineData.canStore(count: count) {
self = .inline(storage.withUnsafeBytes(in: 0..<count) { InlineData($0) })
} else if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(storage, count: count))
} else {
self = .large(LargeSlice(storage, count: count))
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func reserveCapacity(_ minimumCapacity: Int) {
guard minimumCapacity > 0 else { return }
switch self {
case .empty:
if InlineData.canStore(count: minimumCapacity) {
self = .inline(InlineData())
} else if InlineSlice.canStore(count: minimumCapacity) {
self = .slice(InlineSlice(capacity: minimumCapacity))
} else {
self = .large(LargeSlice(capacity: minimumCapacity))
}
case .inline(let inline):
guard minimumCapacity > inline.capacity else { return }
// we know we are going to be heap promoted
if InlineSlice.canStore(count: minimumCapacity) {
var slice = InlineSlice(inline)
slice.reserveCapacity(minimumCapacity)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.reserveCapacity(minimumCapacity)
self = .large(slice)
}
case .slice(var slice):
guard minimumCapacity > slice.capacity else { return }
if InlineSlice.canStore(count: minimumCapacity) {
self = .empty
slice.reserveCapacity(minimumCapacity)
self = .slice(slice)
} else {
var large = LargeSlice(slice)
large.reserveCapacity(minimumCapacity)
self = .large(large)
}
case .large(var slice):
guard minimumCapacity > slice.capacity else { return }
self = .empty
slice.reserveCapacity(minimumCapacity)
self = .large(slice)
}
}
@inlinable // This is @inlinable as reasonably small.
var count: Int {
get {
switch self {
case .empty: return 0
case .inline(let inline): return inline.count
case .slice(let slice): return slice.count
case .large(let slice): return slice.count
}
}
set(newValue) {
// HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee.
// This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame.
@inline(__always)
func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? {
switch representation {
case .empty:
if newValue == 0 {
return nil
} else if InlineData.canStore(count: newValue) {
return .inline(InlineData(count: newValue))
} else if InlineSlice.canStore(count: newValue) {
return .slice(InlineSlice(count: newValue))
} else {
return .large(LargeSlice(count: newValue))
}
case .inline(var inline):
if newValue == 0 {
return .empty
} else if InlineData.canStore(count: newValue) {
guard inline.count != newValue else { return nil }
inline.count = newValue
return .inline(inline)
} else if InlineSlice.canStore(count: newValue) {
var slice = InlineSlice(inline)
slice.count = newValue
return .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.count = newValue
return .large(slice)
}
case .slice(var slice):
if newValue == 0 && slice.startIndex == 0 {
return .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: newValue) {
return .inline(InlineData(slice, count: newValue))
} else if InlineSlice.canStore(count: newValue + slice.startIndex) {
guard slice.count != newValue else { return nil }
representation = .empty // TODO: remove this when mgottesman lands optimizations
slice.count = newValue
return .slice(slice)
} else {
var newSlice = LargeSlice(slice)
newSlice.count = newValue
return .large(newSlice)
}
case .large(var slice):
if newValue == 0 && slice.startIndex == 0 {
return .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: newValue) {
return .inline(InlineData(slice, count: newValue))
} else {
guard slice.count != newValue else { return nil}
representation = .empty // TODO: remove this when mgottesman lands optimizations
slice.count = newValue
return .large(slice)
}
}
}
if let rep = apply(&self, newValue) {
self = rep
}
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
switch self {
case .empty:
let empty = InlineData()
return try empty.withUnsafeBytes(apply)
case .inline(let inline):
return try inline.withUnsafeBytes(apply)
case .slice(let slice):
return try slice.withUnsafeBytes(apply)
case .large(let slice):
return try slice.withUnsafeBytes(apply)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
switch self {
case .empty:
var empty = InlineData()
return try empty.withUnsafeMutableBytes(apply)
case .inline(var inline):
defer { self = .inline(inline) }
return try inline.withUnsafeMutableBytes(apply)
case .slice(var slice):
self = .empty
defer { self = .slice(slice) }
return try slice.withUnsafeMutableBytes(apply)
case .large(var slice):
self = .empty
defer { self = .large(slice) }
return try slice.withUnsafeMutableBytes(apply)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T {
switch self {
case .empty:
return try work(NSData())
case .inline(let inline):
return try inline.withUnsafeBytes {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress ?? UnsafeRawPointer(bitPattern: 0xBAD0)!), length: $0.count, freeWhenDone: false))
}
case .slice(let slice):
return try slice.storage.withInteriorPointerReference(slice.range, work)
case .large(let slice):
return try slice.storage.withInteriorPointerReference(slice.range, work)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
switch self {
case .empty:
var stop = false
block(UnsafeBufferPointer<UInt8>(start: nil, count: 0), 0, &stop)
case .inline(let inline):
inline.withUnsafeBytes {
var stop = false
block(UnsafeBufferPointer<UInt8>(start: $0.baseAddress?.assumingMemoryBound(to: UInt8.self), count: $0.count), 0, &stop)
}
case .slice(let slice):
slice.storage.enumerateBytes(in: slice.range, block)
case .large(let slice):
slice.storage.enumerateBytes(in: slice.range, block)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
switch self {
case .empty:
self = _Representation(buffer)
case .inline(var inline):
if InlineData.canStore(count: inline.count + buffer.count) {
inline.append(contentsOf: buffer)
self = .inline(inline)
} else if InlineSlice.canStore(count: inline.count + buffer.count) {
var newSlice = InlineSlice(inline)
newSlice.append(contentsOf: buffer)
self = .slice(newSlice)
} else {
var newSlice = LargeSlice(inline)
newSlice.append(contentsOf: buffer)
self = .large(newSlice)
}
case .slice(var slice):
if InlineSlice.canStore(count: slice.range.upperBound + buffer.count) {
self = .empty
defer { self = .slice(slice) }
slice.append(contentsOf: buffer)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.append(contentsOf: buffer)
self = .large(newSlice)
}
case .large(var slice):
self = .empty
defer { self = .large(slice) }
slice.append(contentsOf: buffer)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Index>) {
switch self {
case .empty:
if range.upperBound == 0 {
self = .empty
} else if InlineData.canStore(count: range.upperBound) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .inline(InlineData(count: range.upperBound))
} else if InlineSlice.canStore(count: range.upperBound) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .slice(InlineSlice(count: range.upperBound))
} else {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .large(LargeSlice(count: range.upperBound))
}
case .inline(var inline):
if inline.count < range.upperBound {
if InlineSlice.canStore(count: range.upperBound) {
var slice = InlineSlice(inline)
slice.resetBytes(in: range)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.resetBytes(in: range)
self = .large(slice)
}
} else {
inline.resetBytes(in: range)
self = .inline(inline)
}
case .slice(var slice):
if InlineSlice.canStore(count: range.upperBound) {
self = .empty
slice.resetBytes(in: range)
self = .slice(slice)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.resetBytes(in: range)
self = .large(newSlice)
}
case .large(var slice):
self = .empty
slice.resetBytes(in: range)
self = .large(slice)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
switch self {
case .empty:
precondition(subrange.lowerBound == 0 && subrange.upperBound == 0, "range \(subrange) out of bounds of 0..<0")
if cnt == 0 {
return
} else if InlineData.canStore(count: cnt) {
self = .inline(InlineData(UnsafeRawBufferPointer(start: bytes, count: cnt)))
} else if InlineSlice.canStore(count: cnt) {
self = .slice(InlineSlice(UnsafeRawBufferPointer(start: bytes, count: cnt)))
} else {
self = .large(LargeSlice(UnsafeRawBufferPointer(start: bytes, count: cnt)))
}
case .inline(var inline):
let resultingCount = inline.count + cnt - (subrange.upperBound - subrange.lowerBound)
if resultingCount == 0 {
self = .empty
} else if InlineData.canStore(count: resultingCount) {
inline.replaceSubrange(subrange, with: bytes, count: cnt)
self = .inline(inline)
} else if InlineSlice.canStore(count: resultingCount) {
var slice = InlineSlice(inline)
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(slice)
}
case .slice(var slice):
let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound)
if slice.startIndex == 0 && resultingUpper == 0 {
self = .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .inline(InlineData(slice, count: slice.count))
} else if InlineSlice.canStore(count: resultingUpper) {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(slice)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(newSlice)
}
case .large(var slice):
let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound)
if slice.startIndex == 0 && resultingUpper == 0 {
self = .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) {
var inline = InlineData(count: resultingUpper)
inline.withUnsafeMutableBytes { inlineBuffer in
if cnt > 0 {
inlineBuffer.baseAddress?.advanced(by: subrange.lowerBound).copyMemory(from: bytes!, byteCount: cnt)
}
slice.withUnsafeBytes { buffer in
if subrange.lowerBound > 0 {
inlineBuffer.baseAddress?.copyMemory(from: buffer.baseAddress!, byteCount: subrange.lowerBound)
}
if subrange.upperBound < resultingUpper {
inlineBuffer.baseAddress?.advanced(by: subrange.upperBound).copyMemory(from: buffer.baseAddress!.advanced(by: subrange.upperBound), byteCount: resultingUpper - subrange.upperBound)
}
}
}
self = .inline(inline)
} else if InlineSlice.canStore(count: slice.startIndex) && InlineSlice.canStore(count: resultingUpper) {
self = .empty
var newSlice = InlineSlice(slice)
newSlice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(newSlice)
} else {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(slice)
}
}
}
@inlinable // This is @inlinable as trivially forwarding.
subscript(index: Index) -> UInt8 {
get {
switch self {
case .empty: preconditionFailure("index \(index) out of range of 0")
case .inline(let inline): return inline[index]
case .slice(let slice): return slice[index]
case .large(let slice): return slice[index]
}
}
set(newValue) {
switch self {
case .empty: preconditionFailure("index \(index) out of range of 0")
case .inline(var inline):
inline[index] = newValue
self = .inline(inline)
case .slice(var slice):
self = .empty
slice[index] = newValue
self = .slice(slice)
case .large(var slice):
self = .empty
slice[index] = newValue
self = .large(slice)
}
}
}
@inlinable // This is @inlinable as reasonably small.
subscript(bounds: Range<Index>) -> Data {
get {
switch self {
case .empty:
precondition(bounds.lowerBound == 0 && (bounds.upperBound - bounds.lowerBound) == 0, "Range \(bounds) out of bounds 0..<0")
return Data()
case .inline(let inline):
precondition(bounds.upperBound <= inline.count, "Range \(bounds) out of bounds 0..<\(inline.count)")
if bounds.lowerBound == 0 {
var newInline = inline
newInline.count = bounds.upperBound
return Data(representation: .inline(newInline))
} else {
return Data(representation: .slice(InlineSlice(inline, range: bounds)))
}
case .slice(let slice):
precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
if bounds.lowerBound == 0 && bounds.upperBound == 0 {
return Data()
} else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.count) {
return Data(representation: .inline(InlineData(slice, count: bounds.count)))
} else {
var newSlice = slice
newSlice.range = bounds
return Data(representation: .slice(newSlice))
}
case .large(let slice):
precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
if bounds.lowerBound == 0 && bounds.upperBound == 0 {
return Data()
} else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.upperBound) {
return Data(representation: .inline(InlineData(slice, count: bounds.upperBound)))
} else if InlineSlice.canStore(count: bounds.lowerBound) && InlineSlice.canStore(count: bounds.upperBound) {
return Data(representation: .slice(InlineSlice(slice, range: bounds)))
} else {
var newSlice = slice
newSlice.slice = RangeReference(bounds)
return Data(representation: .large(newSlice))
}
}
}
}
@inlinable // This is @inlinable as trivially forwarding.
var startIndex: Int {
switch self {
case .empty: return 0
case .inline: return 0
case .slice(let slice): return slice.startIndex
case .large(let slice): return slice.startIndex
}
}
@inlinable // This is @inlinable as trivially forwarding.
var endIndex: Int {
switch self {
case .empty: return 0
case .inline(let inline): return inline.count
case .slice(let slice): return slice.endIndex
case .large(let slice): return slice.endIndex
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
switch self {
case .empty: return NSData()
case .inline(let inline):
return inline.withUnsafeBytes {
return NSData(bytes: $0.baseAddress, length: $0.count)
}
case .slice(let slice):
return slice.bridgedReference()
case .large(let slice):
return slice.bridgedReference()
}
}
@inlinable // This is @inlinable as trivially forwarding.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) out of bounds 0..<0")
return
case .inline(let inline):
inline.copyBytes(to: pointer, from: range)
case .slice(let slice):
slice.copyBytes(to: pointer, from: range)
case .large(let slice):
slice.copyBytes(to: pointer, from: range)
}
}
@inline(__always) // This should always be inlined into Data.hash(into:).
func hash(into hasher: inout Hasher) {
switch self {
case .empty:
hasher.combine(0)
case .inline(let inline):
inline.hash(into: &hasher)
case .slice(let slice):
slice.hash(into: &hasher)
case .large(let large):
large.hash(into: &hasher)
}
}
}
@usableFromInline internal var _representation: _Representation
// A standard or custom deallocator for `Data`.
///
/// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated.
public enum Deallocator {
/// Use a virtual memory deallocator.
#if !DEPLOYMENT_RUNTIME_SWIFT
case virtualMemory
#endif
/// Use `munmap`.
case unmap
/// Use `free`.
case free
/// Do nothing upon deallocation.
case none
/// A custom deallocator.
case custom((UnsafeMutableRawPointer, Int) -> Void)
@usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
#if DEPLOYMENT_RUNTIME_SWIFT
switch self {
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return b
}
#else
switch self {
case .virtualMemory:
return { NSDataDeallocatorVM($0, $1) }
case .unmap:
return { NSDataDeallocatorUnmap($0, $1) }
case .free:
return { NSDataDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return b
}
#endif
}
}
// MARK: -
// MARK: Init methods
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
@inlinable // This is @inlinable as a trivial initializer.
public init(bytes: UnsafeRawPointer, count: Int) {
_representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count))
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a trivial, generic initializer.
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
_representation = _Representation(UnsafeRawBufferPointer(buffer))
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a trivial, generic initializer.
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
_representation = _Representation(UnsafeRawBufferPointer(buffer))
}
/// Initialize a `Data` with a repeating byte pattern
///
/// - parameter repeatedValue: A byte to initialize the pattern
/// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
@inlinable // This is @inlinable as a convenience initializer.
public init(repeating repeatedValue: UInt8, count: Int) {
self.init(count: count)
withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in
memset(buffer.baseAddress, Int32(repeatedValue), buffer.count)
}
}
/// Initialize a `Data` with the specified size.
///
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
///
/// This method sets the `count` of the data to 0.
///
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
///
/// - parameter capacity: The size of the data.
@inlinable // This is @inlinable as a trivial initializer.
public init(capacity: Int) {
_representation = _Representation(capacity: capacity)
}
/// Initialize a `Data` with the specified count of zeroed bytes.
///
/// - parameter count: The number of bytes the data initially contains.
@inlinable // This is @inlinable as a trivial initializer.
public init(count: Int) {
_representation = _Representation(count: count)
}
/// Initialize an empty `Data`.
@inlinable // This is @inlinable as a trivial initializer.
public init() {
_representation = .empty
}
/// Initialize a `Data` without copying the bytes.
///
/// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
@inlinable // This is @inlinable as a trivial initializer.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
let whichDeallocator = deallocator._deallocator
if count == 0 {
deallocator._deallocator(bytes, count)
_representation = .empty
} else {
_representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count)
}
}
/// Initialize a `Data` with the contents of a `URL`.
///
/// - parameter url: The `URL` to read.
/// - parameter options: Options for the read operation. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if `url` cannot be read.
@inlinable // This is @inlinable as a convenience initializer.
public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws {
let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
self.init(referencing: d)
}
/// Initialize a `Data` from a Base-64 encoded String using the given options.
///
/// Returns nil when the input is not recognized as valid Base-64.
/// - parameter base64String: The string to parse.
/// - parameter options: Encoding options. Default value is `[]`.
@inlinable // This is @inlinable as a convenience initializer.
public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
self.init(referencing: d)
} else {
return nil
}
}
/// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
///
/// Returns nil when the input is not recognized as valid Base-64.
///
/// - parameter base64Data: Base-64, UTF-8 encoded input data.
/// - parameter options: Decoding options. Default value is `[]`.
@inlinable // This is @inlinable as a convenience initializer.
public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
self.init(referencing: d)
} else {
return nil
}
}
/// Initialize a `Data` by adopting a reference type.
///
/// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
///
/// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
///
/// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
public init(referencing reference: __shared NSData) {
// This is not marked as inline because _providesConcreteBacking would need to be marked as usable from inline however that is a dynamic lookup in objc contexts.
let length = reference.length
if length == 0 {
_representation = .empty
} else {
#if DEPLOYMENT_RUNTIME_SWIFT
let providesConcreteBacking = reference._providesConcreteBacking()
#else
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
#endif
if providesConcreteBacking {
_representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length)
} else {
_representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length)
}
}
}
// slightly faster paths for common sequences
@inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer.
public init<S: Sequence>(_ elements: S) where S.Element == UInt8 {
// If the sequence is already contiguous, access the underlying raw memory directly.
if let contiguous = elements as? ContiguousBytes {
_representation = contiguous.withUnsafeBytes { return _Representation($0) }
return
}
// The sequence might still be able to provide direct access to typed memory.
// NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences.
let representation = elements.withContiguousStorageIfAvailable {
_Representation(UnsafeRawBufferPointer($0))
}
if let representation = representation {
_representation = representation
return
}
// Copy as much as we can in one shot from the sequence.
let underestimatedCount = elements.underestimatedCount
_representation = _Representation(count: underestimatedCount)
var (iter, endIndex): (S.Iterator, Int) = _representation.withUnsafeMutableBytes { buffer in
let start = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
let b = UnsafeMutableBufferPointer(start: start, count: buffer.count)
return elements._copyContents(initializing: b)
}
guard endIndex == _representation.count else {
// We can't trap here. We have to allow an underfilled buffer
// to emulate the previous implementation.
_representation.replaceSubrange(endIndex ..< _representation.endIndex, with: nil, count: 0)
return
}
// Append the rest byte-wise, buffering through an InlineData.
var buffer = InlineData()
while let element = iter.next() {
buffer.append(byte: element)
if buffer.count == buffer.capacity {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
// If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
if buffer.count > 0 {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
@available(swift, introduced: 4.2)
@available(swift, deprecated: 5, message: "use `init(_:)` instead")
public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 {
self.init(elements)
}
@available(swift, obsoleted: 4.2)
public init(bytes: Array<UInt8>) {
self.init(bytes)
}
@available(swift, obsoleted: 4.2)
public init(bytes: ArraySlice<UInt8>) {
self.init(bytes)
}
@inlinable // This is @inlinable as a trivial initializer.
internal init(representation: _Representation) {
_representation = representation
}
// -----------------------------------
// MARK: - Properties and Functions
@inlinable // This is @inlinable as trivially forwarding.
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_representation.reserveCapacity(minimumCapacity)
}
/// The number of bytes in the data.
@inlinable // This is @inlinable as trivially forwarding.
public var count: Int {
get {
return _representation.count
}
set(newValue) {
precondition(newValue >= 0, "count must not be negative")
_representation.count = newValue
}
}
@inlinable // This is @inlinable as trivially computable.
public var regions: CollectionOfOne<Data> {
return CollectionOfOne(self)
}
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@available(swift, deprecated: 5, message: "use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead")
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeBytes {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeBytes(body)
}
/// Mutate the bytes in the data.
///
/// This function assumes that you are mutating the contents.
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@available(swift, deprecated: 5, message: "use `withUnsafeMutableBytes<R>(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead")
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeMutableBytes {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeMutableBytes(body)
}
// MARK: -
// MARK: Copy Bytes
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count))
}
@inlinable // This is @inlinable as trivially forwarding.
internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
if range.isEmpty { return }
_representation.copyBytes(to: pointer, from: range)
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: range)
}
// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
@inlinable // This is @inlinable as generic and reasonably small.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
guard !copyRange.isEmpty else { return 0 }
_copyBytesHelper(to: buffer.baseAddress!, from: copyRange)
return copyRange.upperBound - copyRange.lowerBound
}
// MARK: -
#if !DEPLOYMENT_RUNTIME_SWIFT
private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool {
// Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation.
if !options.contains(.atomic) {
#if os(macOS)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
// this should not be marked as inline since in objc contexts we correct atomicity via _shouldUseNonAtomicWriteReimplementation
try _representation.withInteriorPointerReference {
#if DEPLOYMENT_RUNTIME_SWIFT
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
#else
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error: NSError? = nil
guard __NSDataWriteToURL($0, url, options, &error) else { throw error! }
} else {
try $0.write(to: url, options: options)
}
#endif
}
}
// MARK: -
/// Find the given `Data` in the content of this `Data`.
///
/// - parameter dataToFind: The data to be searched for.
/// - parameter options: Options for the search. Default value is `[]`.
/// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
/// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
/// - precondition: `range` must be in the bounds of the Data.
public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
let nsRange : NSRange
if let r = range {
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
} else {
nsRange = NSRange(location: 0, length: count)
}
let result = _representation.withInteriorPointerReference {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
}
/// Enumerate the contents of the data.
///
/// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes.
/// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
@available(swift, deprecated: 5, message: "use `regions` or `for-in` instead")
public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
_representation.enumerateBytes(block)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
if buffer.isEmpty { return }
_representation.append(contentsOf: UnsafeRawBufferPointer(buffer))
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
_append(UnsafeBufferPointer(start: bytes, count: count))
}
public mutating func append(_ other: Data) {
guard !other.isEmpty else { return }
other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
_representation.append(contentsOf: buffer)
}
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
_append(buffer)
}
@inlinable // This is @inlinable as trivially forwarding.
public mutating func append(contentsOf bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
_append(buffer)
}
}
@inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial.
public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element {
// If the sequence is already contiguous, access the underlying raw memory directly.
if let contiguous = elements as? ContiguousBytes {
contiguous.withUnsafeBytes {
_representation.append(contentsOf: $0)
}
return
}
// The sequence might still be able to provide direct access to typed memory.
// NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences.
let appended: Void? = elements.withContiguousStorageIfAvailable {
_representation.append(contentsOf: UnsafeRawBufferPointer($0))
}
guard appended == nil else { return }
// The sequence is really not contiguous.
// Copy as much as we can in one shot.
let underestimatedCount = elements.underestimatedCount
let originalCount = _representation.count
resetBytes(in: self.endIndex ..< self.endIndex + underestimatedCount)
var (iter, copiedCount): (S.Iterator, Int) = _representation.withUnsafeMutableBytes { buffer in
assert(buffer.count == originalCount + underestimatedCount)
let start = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self) + originalCount
let b = UnsafeMutableBufferPointer(start: start, count: buffer.count - originalCount)
return elements._copyContents(initializing: b)
}
guard copiedCount == underestimatedCount else {
// We can't trap here. We have to allow an underfilled buffer
// to emulate the previous implementation.
_representation.replaceSubrange(startIndex + originalCount + copiedCount ..< endIndex, with: nil, count: 0)
return
}
// Append the rest byte-wise, buffering through an InlineData.
var buffer = InlineData()
while let element = iter.next() {
buffer.append(byte: element)
if buffer.count == buffer.capacity {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
// If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
if buffer.count > 0 {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
// MARK: -
/// Set a region of the data to `0`.
///
/// If `range` exceeds the bounds of the data, then the data is resized to fit.
/// - parameter range: The range in the data to set to `0`.
@inlinable // This is @inlinable as trivially forwarding.
public mutating func resetBytes(in range: Range<Index>) {
// it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
precondition(range.lowerBound >= 0, "Ranges must not be negative bounds")
precondition(range.upperBound >= 0, "Ranges must not be negative bounds")
_representation.resetBytes(in: range)
}
/// Replace a region of bytes in the data with new data.
///
/// This will resize the data if required, to fit the entire contents of `data`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
/// - parameter data: The replacement data.
@inlinable // This is @inlinable as trivially forwarding.
public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
_representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count)
}
}
/// Replace a region of bytes in the data with new bytes from a buffer.
///
/// This will resize the data if required, to fit the entire contents of `buffer`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter buffer: The replacement bytes.
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
guard !buffer.isEmpty else { return }
replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
}
/// Replace a region of bytes in the data with new bytes from a collection.
///
/// This will resize the data if required, to fit the entire contents of `newElements`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter newElements: The replacement bytes.
@inlinable // This is @inlinable as generic and reasonably small.
public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
// If the collection is already contiguous, access the underlying raw memory directly.
if let contiguous = newElements as? ContiguousBytes {
contiguous.withUnsafeBytes { buffer in
_representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count)
}
return
}
// The collection might still be able to provide direct access to typed memory.
// NOTE: It's safe to do this because we're already guarding on ByteCollection's element as `UInt8`. This would not be safe on arbitrary collections.
let replaced: Void? = newElements.withContiguousStorageIfAvailable { buffer in
_representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count)
}
guard replaced == nil else { return }
let totalCount = Int(newElements.count)
_withStackOrHeapBuffer(capacity: totalCount) { buffer in
var (iterator, index) = newElements._copyContents(initializing: buffer)
precondition(index == buffer.endIndex, "Collection has less elements than its count")
precondition(iterator.next() == nil, "Collection has more elements than its count")
_representation.replaceSubrange(subrange, with: buffer.baseAddress, count: totalCount)
}
}
@inlinable // This is @inlinable as trivially forwarding.
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
_representation.replaceSubrange(subrange, with: bytes, count: cnt)
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
public func subdata(in range: Range<Index>) -> Data {
if isEmpty || range.upperBound - range.lowerBound == 0 {
return Data()
}
let slice = self[range]
return slice.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> Data in
return Data(bytes: buffer.baseAddress!, count: buffer.count)
}
}
// MARK: -
//
/// Returns a Base-64 encoded string.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded string.
@inlinable // This is @inlinable as trivially forwarding.
public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
return _representation.withInteriorPointerReference {
return $0.base64EncodedString(options: options)
}
}
/// Returns a Base-64 encoded `Data`.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded data.
@inlinable // This is @inlinable as trivially forwarding.
public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
return _representation.withInteriorPointerReference {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
@inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together.
public func hash(into hasher: inout Hasher) {
_representation.hash(into: &hasher)
}
public func advanced(by amount: Int) -> Data {
let length = count - amount
precondition(length > 0)
return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in
return Data(bytes: ptr.baseAddress!.advanced(by: amount), count: length)
}
}
// MARK: -
// MARK: -
// MARK: Index and Subscript
/// Sets or returns the byte at the specified index.
@inlinable // This is @inlinable as trivially forwarding.
public subscript(index: Index) -> UInt8 {
get {
return _representation[index]
}
set(newValue) {
_representation[index] = newValue
}
}
@inlinable // This is @inlinable as trivially forwarding.
public subscript(bounds: Range<Index>) -> Data {
get {
return _representation[bounds]
}
set {
replaceSubrange(bounds, with: newValue)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
where R.Bound: FixedWidthInteger {
get {
let lower = R.Bound(startIndex)
let upper = R.Bound(endIndex)
let range = rangeExpression.relative(to: lower..<upper)
let start = Int(range.lowerBound)
let end = Int(range.upperBound)
let r: Range<Int> = start..<end
return _representation[r]
}
set {
let lower = R.Bound(startIndex)
let upper = R.Bound(endIndex)
let range = rangeExpression.relative(to: lower..<upper)
let start = Int(range.lowerBound)
let end = Int(range.upperBound)
let r: Range<Int> = start..<end
replaceSubrange(r, with: newValue)
}
}
/// The start `Index` in the data.
@inlinable // This is @inlinable as trivially forwarding.
public var startIndex: Index {
get {
return _representation.startIndex
}
}
/// The end `Index` into the data.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
@inlinable // This is @inlinable as trivially forwarding.
public var endIndex: Index {
get {
return _representation.endIndex
}
}
@inlinable // This is @inlinable as trivially computable.
public func index(before i: Index) -> Index {
return i - 1
}
@inlinable // This is @inlinable as trivially computable.
public func index(after i: Index) -> Index {
return i + 1
}
@inlinable // This is @inlinable as trivially computable.
public var indices: Range<Int> {
get {
return startIndex..<endIndex
}
}
@inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages.
public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
let cnt = Swift.min(count, buffer.count)
withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
_ = memcpy(UnsafeMutableRawPointer(buffer.baseAddress), bytes.baseAddress, cnt)
}
return (Iterator(self, at: startIndex + cnt), buffer.index(buffer.startIndex, offsetBy: cnt))
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
@inlinable // This is @inlinable as trivially computable.
public func makeIterator() -> Data.Iterator {
return Iterator(self, at: startIndex)
}
public struct Iterator : IteratorProtocol {
@usableFromInline
internal typealias Buffer = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
@usableFromInline internal let _data: Data
@usableFromInline internal var _buffer: Buffer
@usableFromInline internal var _idx: Data.Index
@usableFromInline internal let _endIdx: Data.Index
@usableFromInline // This is @usableFromInline as a non-trivial initializer.
internal init(_ data: Data, at loc: Data.Index) {
// The let vars prevent this from being marked as @inlinable
_data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = loc
_endIdx = data.endIndex
let bufferSize = MemoryLayout<Buffer>.size
Swift.withUnsafeMutableBytes(of: &_buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
let bufferIdx = (loc - data.startIndex) % bufferSize
data.copyBytes(to: ptr, from: (loc - bufferIdx)..<(data.endIndex - (loc - bufferIdx) > bufferSize ? (loc - bufferIdx) + bufferSize : data.endIndex))
}
}
public mutating func next() -> UInt8? {
let idx = _idx
let bufferSize = MemoryLayout<Buffer>.size
guard idx < _endIdx else { return nil }
_idx += 1
let bufferIdx = (idx - _data.startIndex) % bufferSize
if bufferIdx == 0 {
var buffer = _buffer
Swift.withUnsafeMutableBytes(of: &buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
// populate the buffer
_data.copyBytes(to: ptr, from: idx..<(_endIdx - idx > bufferSize ? idx + bufferSize : _endIdx))
}
_buffer = buffer
}
return Swift.withUnsafeMutableBytes(of: &_buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
return ptr[bufferIdx]
}
}
}
// MARK: -
//
@available(*, unavailable, renamed: "count")
public var length: Int {
get { fatalError() }
set { fatalError() }
}
@available(*, unavailable, message: "use withUnsafeBytes instead")
public var bytes: UnsafeRawPointer { fatalError() }
@available(*, unavailable, message: "use withUnsafeMutableBytes instead")
public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
/// Returns `true` if the two `Data` arguments are equal.
@inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change.
public static func ==(d1 : Data, d2 : Data) -> Bool {
let length1 = d1.count
if length1 != d2.count {
return false
}
if length1 > 0 {
return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in
return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in
return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0
}
}
}
return true
}
}
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A human-readable description for the data.
public var description: String {
return "\(self.count) bytes"
}
/// A human-readable debug description for the data.
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let nBytes = self.count
var children: [(label: String?, value: Any)] = []
children.append((label: "count", value: nBytes))
self.withUnsafeBytes { (bytes : UnsafeRawBufferPointer) in
children.append((label: "pointer", value: bytes.baseAddress!))
}
// Minimal size data is output as an array
if nBytes < 64 {
children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)])))
}
let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension Data {
@available(*, unavailable, renamed: "copyBytes(to:count:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { }
@available(*, unavailable, renamed: "copyBytes(to:from:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { }
}
/// Provides bridging functionality for struct Data to class NSData and vice-versa.
extension Data : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSData {
return _representation.bridgedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
return true
}
// @_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data {
guard let src = source else { return Data() }
return Data(referencing: src)
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
extension Data : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
try container.encode(contentsOf: buffer)
}
}
}
| 45.319902 | 352 | 0.600968 |
0ea564a83b65a374f90537652b8c5345c3fc3304 | 861 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Dispatch
let q = dispatch_queue_create("", nil) // expected-error {{'dispatch_queue_create' has been replaced by 'DispatchQueue.init(label:qos:attributes:autoreleaseFrequency:target:)'}}
_ = dispatch_queue_get_label(q) // expected-error {{'dispatch_queue_get_label' has been replaced by property 'DispatchQueue.label'}}
_ = dispatch_get_global_queue(0, 0) // expected-error {{'dispatch_get_global_queue' has been replaced by 'DispatchQueue.global(attributes:)'}}
_ = dispatch_source_create(OpaquePointer(bitPattern: ~0)!, 0, 0, nil) // expected-error {{'dispatch_source_create' is unavailable: Use DispatchSource class methods}}
_ = dispatch_get_main_queue() // expected-error {{'dispatch_get_main_queue()' has been replaced by property 'DispatchQueue.main'}}
_ = DispatchQueue.main
| 53.8125 | 177 | 0.778165 |
766fa05cccdb8db9019ac03a6632ec5714877a9d | 273 | //
// ViewController.swift
// TabBarDemo
//
// Created by Yang Yang on 11/1/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 13.65 | 52 | 0.644689 |
14f5db7dc6b01cfe9626551a0b02490b5ba76d37 | 248,346 | // Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment
// -- Generated Code; do not edit --
//
// RDSModelDefaultInstances.swift
// RDSModel
//
import Foundation
public extension AccountAttributesMessage {
/**
Default instance of the AccountAttributesMessage structure.
*/
static let __default: RDSModel.AccountAttributesMessage = {
let defaultInstance = RDSModel.AccountAttributesMessage(
accountQuotas: nil)
return defaultInstance
}()
}
public extension AccountAttributesMessageForDescribeAccountAttributes {
/**
Default instance of the AccountAttributesMessageForDescribeAccountAttributes structure.
*/
static let __default: RDSModel.AccountAttributesMessageForDescribeAccountAttributes = {
let defaultInstance = RDSModel.AccountAttributesMessageForDescribeAccountAttributes(
describeAccountAttributesResult: AccountAttributesMessage.__default)
return defaultInstance
}()
}
public extension AccountQuota {
/**
Default instance of the AccountQuota structure.
*/
static let __default: RDSModel.AccountQuota = {
let defaultInstance = RDSModel.AccountQuota(
accountQuotaName: nil,
max: nil,
used: nil)
return defaultInstance
}()
}
public extension AddRoleToDBClusterMessage {
/**
Default instance of the AddRoleToDBClusterMessage structure.
*/
static let __default: RDSModel.AddRoleToDBClusterMessage = {
let defaultInstance = RDSModel.AddRoleToDBClusterMessage(
dBClusterIdentifier: "value",
featureName: nil,
roleArn: "value")
return defaultInstance
}()
}
public extension AddRoleToDBInstanceMessage {
/**
Default instance of the AddRoleToDBInstanceMessage structure.
*/
static let __default: RDSModel.AddRoleToDBInstanceMessage = {
let defaultInstance = RDSModel.AddRoleToDBInstanceMessage(
dBInstanceIdentifier: "value",
featureName: "value",
roleArn: "value")
return defaultInstance
}()
}
public extension AddSourceIdentifierToSubscriptionMessage {
/**
Default instance of the AddSourceIdentifierToSubscriptionMessage structure.
*/
static let __default: RDSModel.AddSourceIdentifierToSubscriptionMessage = {
let defaultInstance = RDSModel.AddSourceIdentifierToSubscriptionMessage(
sourceIdentifier: "value",
subscriptionName: "value")
return defaultInstance
}()
}
public extension AddSourceIdentifierToSubscriptionResult {
/**
Default instance of the AddSourceIdentifierToSubscriptionResult structure.
*/
static let __default: RDSModel.AddSourceIdentifierToSubscriptionResult = {
let defaultInstance = RDSModel.AddSourceIdentifierToSubscriptionResult(
eventSubscription: nil)
return defaultInstance
}()
}
public extension AddSourceIdentifierToSubscriptionResultForAddSourceIdentifierToSubscription {
/**
Default instance of the AddSourceIdentifierToSubscriptionResultForAddSourceIdentifierToSubscription structure.
*/
static let __default: RDSModel.AddSourceIdentifierToSubscriptionResultForAddSourceIdentifierToSubscription = {
let defaultInstance = RDSModel.AddSourceIdentifierToSubscriptionResultForAddSourceIdentifierToSubscription(
addSourceIdentifierToSubscriptionResult: AddSourceIdentifierToSubscriptionResult.__default)
return defaultInstance
}()
}
public extension AddTagsToResourceMessage {
/**
Default instance of the AddTagsToResourceMessage structure.
*/
static let __default: RDSModel.AddTagsToResourceMessage = {
let defaultInstance = RDSModel.AddTagsToResourceMessage(
resourceName: "value",
tags: [])
return defaultInstance
}()
}
public extension ApplyPendingMaintenanceActionMessage {
/**
Default instance of the ApplyPendingMaintenanceActionMessage structure.
*/
static let __default: RDSModel.ApplyPendingMaintenanceActionMessage = {
let defaultInstance = RDSModel.ApplyPendingMaintenanceActionMessage(
applyAction: "value",
optInType: "value",
resourceIdentifier: "value")
return defaultInstance
}()
}
public extension ApplyPendingMaintenanceActionResult {
/**
Default instance of the ApplyPendingMaintenanceActionResult structure.
*/
static let __default: RDSModel.ApplyPendingMaintenanceActionResult = {
let defaultInstance = RDSModel.ApplyPendingMaintenanceActionResult(
resourcePendingMaintenanceActions: nil)
return defaultInstance
}()
}
public extension ApplyPendingMaintenanceActionResultForApplyPendingMaintenanceAction {
/**
Default instance of the ApplyPendingMaintenanceActionResultForApplyPendingMaintenanceAction structure.
*/
static let __default: RDSModel.ApplyPendingMaintenanceActionResultForApplyPendingMaintenanceAction = {
let defaultInstance = RDSModel.ApplyPendingMaintenanceActionResultForApplyPendingMaintenanceAction(
applyPendingMaintenanceActionResult: ApplyPendingMaintenanceActionResult.__default)
return defaultInstance
}()
}
public extension AuthorizationAlreadyExistsFault {
/**
Default instance of the AuthorizationAlreadyExistsFault structure.
*/
static let __default: RDSModel.AuthorizationAlreadyExistsFault = {
let defaultInstance = RDSModel.AuthorizationAlreadyExistsFault()
return defaultInstance
}()
}
public extension AuthorizationNotFoundFault {
/**
Default instance of the AuthorizationNotFoundFault structure.
*/
static let __default: RDSModel.AuthorizationNotFoundFault = {
let defaultInstance = RDSModel.AuthorizationNotFoundFault()
return defaultInstance
}()
}
public extension AuthorizationQuotaExceededFault {
/**
Default instance of the AuthorizationQuotaExceededFault structure.
*/
static let __default: RDSModel.AuthorizationQuotaExceededFault = {
let defaultInstance = RDSModel.AuthorizationQuotaExceededFault()
return defaultInstance
}()
}
public extension AuthorizeDBSecurityGroupIngressMessage {
/**
Default instance of the AuthorizeDBSecurityGroupIngressMessage structure.
*/
static let __default: RDSModel.AuthorizeDBSecurityGroupIngressMessage = {
let defaultInstance = RDSModel.AuthorizeDBSecurityGroupIngressMessage(
cIDRIP: nil,
dBSecurityGroupName: "value",
eC2SecurityGroupId: nil,
eC2SecurityGroupName: nil,
eC2SecurityGroupOwnerId: nil)
return defaultInstance
}()
}
public extension AuthorizeDBSecurityGroupIngressResult {
/**
Default instance of the AuthorizeDBSecurityGroupIngressResult structure.
*/
static let __default: RDSModel.AuthorizeDBSecurityGroupIngressResult = {
let defaultInstance = RDSModel.AuthorizeDBSecurityGroupIngressResult(
dBSecurityGroup: nil)
return defaultInstance
}()
}
public extension AuthorizeDBSecurityGroupIngressResultForAuthorizeDBSecurityGroupIngress {
/**
Default instance of the AuthorizeDBSecurityGroupIngressResultForAuthorizeDBSecurityGroupIngress structure.
*/
static let __default: RDSModel.AuthorizeDBSecurityGroupIngressResultForAuthorizeDBSecurityGroupIngress = {
let defaultInstance = RDSModel.AuthorizeDBSecurityGroupIngressResultForAuthorizeDBSecurityGroupIngress(
authorizeDBSecurityGroupIngressResult: AuthorizeDBSecurityGroupIngressResult.__default)
return defaultInstance
}()
}
public extension AvailabilityZone {
/**
Default instance of the AvailabilityZone structure.
*/
static let __default: RDSModel.AvailabilityZone = {
let defaultInstance = RDSModel.AvailabilityZone(
name: nil)
return defaultInstance
}()
}
public extension AvailableProcessorFeature {
/**
Default instance of the AvailableProcessorFeature structure.
*/
static let __default: RDSModel.AvailableProcessorFeature = {
let defaultInstance = RDSModel.AvailableProcessorFeature(
allowedValues: nil,
defaultValue: nil,
name: nil)
return defaultInstance
}()
}
public extension BacktrackDBClusterMessage {
/**
Default instance of the BacktrackDBClusterMessage structure.
*/
static let __default: RDSModel.BacktrackDBClusterMessage = {
let defaultInstance = RDSModel.BacktrackDBClusterMessage(
backtrackTo: "2013-02-18T17:00:00Z",
dBClusterIdentifier: "value",
force: nil,
useEarliestTimeOnPointInTimeUnavailable: nil)
return defaultInstance
}()
}
public extension BackupPolicyNotFoundFault {
/**
Default instance of the BackupPolicyNotFoundFault structure.
*/
static let __default: RDSModel.BackupPolicyNotFoundFault = {
let defaultInstance = RDSModel.BackupPolicyNotFoundFault()
return defaultInstance
}()
}
public extension CancelExportTaskMessage {
/**
Default instance of the CancelExportTaskMessage structure.
*/
static let __default: RDSModel.CancelExportTaskMessage = {
let defaultInstance = RDSModel.CancelExportTaskMessage(
exportTaskIdentifier: "value")
return defaultInstance
}()
}
public extension Certificate {
/**
Default instance of the Certificate structure.
*/
static let __default: RDSModel.Certificate = {
let defaultInstance = RDSModel.Certificate(
certificateArn: nil,
certificateIdentifier: nil,
certificateType: nil,
customerOverride: nil,
customerOverrideValidTill: nil,
thumbprint: nil,
validFrom: nil,
validTill: nil)
return defaultInstance
}()
}
public extension CertificateMessage {
/**
Default instance of the CertificateMessage structure.
*/
static let __default: RDSModel.CertificateMessage = {
let defaultInstance = RDSModel.CertificateMessage(
certificates: nil,
marker: nil)
return defaultInstance
}()
}
public extension CertificateMessageForDescribeCertificates {
/**
Default instance of the CertificateMessageForDescribeCertificates structure.
*/
static let __default: RDSModel.CertificateMessageForDescribeCertificates = {
let defaultInstance = RDSModel.CertificateMessageForDescribeCertificates(
describeCertificatesResult: CertificateMessage.__default)
return defaultInstance
}()
}
public extension CertificateNotFoundFault {
/**
Default instance of the CertificateNotFoundFault structure.
*/
static let __default: RDSModel.CertificateNotFoundFault = {
let defaultInstance = RDSModel.CertificateNotFoundFault()
return defaultInstance
}()
}
public extension CharacterSet {
/**
Default instance of the CharacterSet structure.
*/
static let __default: RDSModel.CharacterSet = {
let defaultInstance = RDSModel.CharacterSet(
characterSetDescription: nil,
characterSetName: nil)
return defaultInstance
}()
}
public extension CloudwatchLogsExportConfiguration {
/**
Default instance of the CloudwatchLogsExportConfiguration structure.
*/
static let __default: RDSModel.CloudwatchLogsExportConfiguration = {
let defaultInstance = RDSModel.CloudwatchLogsExportConfiguration(
disableLogTypes: nil,
enableLogTypes: nil)
return defaultInstance
}()
}
public extension ConnectionPoolConfiguration {
/**
Default instance of the ConnectionPoolConfiguration structure.
*/
static let __default: RDSModel.ConnectionPoolConfiguration = {
let defaultInstance = RDSModel.ConnectionPoolConfiguration(
connectionBorrowTimeout: nil,
initQuery: nil,
maxConnectionsPercent: nil,
maxIdleConnectionsPercent: nil,
sessionPinningFilters: nil)
return defaultInstance
}()
}
public extension ConnectionPoolConfigurationInfo {
/**
Default instance of the ConnectionPoolConfigurationInfo structure.
*/
static let __default: RDSModel.ConnectionPoolConfigurationInfo = {
let defaultInstance = RDSModel.ConnectionPoolConfigurationInfo(
connectionBorrowTimeout: nil,
initQuery: nil,
maxConnectionsPercent: nil,
maxIdleConnectionsPercent: nil,
sessionPinningFilters: nil)
return defaultInstance
}()
}
public extension CopyDBClusterParameterGroupMessage {
/**
Default instance of the CopyDBClusterParameterGroupMessage structure.
*/
static let __default: RDSModel.CopyDBClusterParameterGroupMessage = {
let defaultInstance = RDSModel.CopyDBClusterParameterGroupMessage(
sourceDBClusterParameterGroupIdentifier: "value",
tags: nil,
targetDBClusterParameterGroupDescription: "value",
targetDBClusterParameterGroupIdentifier: "value")
return defaultInstance
}()
}
public extension CopyDBClusterParameterGroupResult {
/**
Default instance of the CopyDBClusterParameterGroupResult structure.
*/
static let __default: RDSModel.CopyDBClusterParameterGroupResult = {
let defaultInstance = RDSModel.CopyDBClusterParameterGroupResult(
dBClusterParameterGroup: nil)
return defaultInstance
}()
}
public extension CopyDBClusterParameterGroupResultForCopyDBClusterParameterGroup {
/**
Default instance of the CopyDBClusterParameterGroupResultForCopyDBClusterParameterGroup structure.
*/
static let __default: RDSModel.CopyDBClusterParameterGroupResultForCopyDBClusterParameterGroup = {
let defaultInstance = RDSModel.CopyDBClusterParameterGroupResultForCopyDBClusterParameterGroup(
copyDBClusterParameterGroupResult: CopyDBClusterParameterGroupResult.__default)
return defaultInstance
}()
}
public extension CopyDBClusterSnapshotMessage {
/**
Default instance of the CopyDBClusterSnapshotMessage structure.
*/
static let __default: RDSModel.CopyDBClusterSnapshotMessage = {
let defaultInstance = RDSModel.CopyDBClusterSnapshotMessage(
copyTags: nil,
kmsKeyId: nil,
preSignedUrl: nil,
sourceDBClusterSnapshotIdentifier: "value",
tags: nil,
targetDBClusterSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension CopyDBClusterSnapshotResult {
/**
Default instance of the CopyDBClusterSnapshotResult structure.
*/
static let __default: RDSModel.CopyDBClusterSnapshotResult = {
let defaultInstance = RDSModel.CopyDBClusterSnapshotResult(
dBClusterSnapshot: nil)
return defaultInstance
}()
}
public extension CopyDBClusterSnapshotResultForCopyDBClusterSnapshot {
/**
Default instance of the CopyDBClusterSnapshotResultForCopyDBClusterSnapshot structure.
*/
static let __default: RDSModel.CopyDBClusterSnapshotResultForCopyDBClusterSnapshot = {
let defaultInstance = RDSModel.CopyDBClusterSnapshotResultForCopyDBClusterSnapshot(
copyDBClusterSnapshotResult: CopyDBClusterSnapshotResult.__default)
return defaultInstance
}()
}
public extension CopyDBParameterGroupMessage {
/**
Default instance of the CopyDBParameterGroupMessage structure.
*/
static let __default: RDSModel.CopyDBParameterGroupMessage = {
let defaultInstance = RDSModel.CopyDBParameterGroupMessage(
sourceDBParameterGroupIdentifier: "value",
tags: nil,
targetDBParameterGroupDescription: "value",
targetDBParameterGroupIdentifier: "value")
return defaultInstance
}()
}
public extension CopyDBParameterGroupResult {
/**
Default instance of the CopyDBParameterGroupResult structure.
*/
static let __default: RDSModel.CopyDBParameterGroupResult = {
let defaultInstance = RDSModel.CopyDBParameterGroupResult(
dBParameterGroup: nil)
return defaultInstance
}()
}
public extension CopyDBParameterGroupResultForCopyDBParameterGroup {
/**
Default instance of the CopyDBParameterGroupResultForCopyDBParameterGroup structure.
*/
static let __default: RDSModel.CopyDBParameterGroupResultForCopyDBParameterGroup = {
let defaultInstance = RDSModel.CopyDBParameterGroupResultForCopyDBParameterGroup(
copyDBParameterGroupResult: CopyDBParameterGroupResult.__default)
return defaultInstance
}()
}
public extension CopyDBSnapshotMessage {
/**
Default instance of the CopyDBSnapshotMessage structure.
*/
static let __default: RDSModel.CopyDBSnapshotMessage = {
let defaultInstance = RDSModel.CopyDBSnapshotMessage(
copyTags: nil,
kmsKeyId: nil,
optionGroupName: nil,
preSignedUrl: nil,
sourceDBSnapshotIdentifier: "value",
tags: nil,
targetCustomAvailabilityZone: nil,
targetDBSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension CopyDBSnapshotResult {
/**
Default instance of the CopyDBSnapshotResult structure.
*/
static let __default: RDSModel.CopyDBSnapshotResult = {
let defaultInstance = RDSModel.CopyDBSnapshotResult(
dBSnapshot: nil)
return defaultInstance
}()
}
public extension CopyDBSnapshotResultForCopyDBSnapshot {
/**
Default instance of the CopyDBSnapshotResultForCopyDBSnapshot structure.
*/
static let __default: RDSModel.CopyDBSnapshotResultForCopyDBSnapshot = {
let defaultInstance = RDSModel.CopyDBSnapshotResultForCopyDBSnapshot(
copyDBSnapshotResult: CopyDBSnapshotResult.__default)
return defaultInstance
}()
}
public extension CopyOptionGroupMessage {
/**
Default instance of the CopyOptionGroupMessage structure.
*/
static let __default: RDSModel.CopyOptionGroupMessage = {
let defaultInstance = RDSModel.CopyOptionGroupMessage(
sourceOptionGroupIdentifier: "value",
tags: nil,
targetOptionGroupDescription: "value",
targetOptionGroupIdentifier: "value")
return defaultInstance
}()
}
public extension CopyOptionGroupResult {
/**
Default instance of the CopyOptionGroupResult structure.
*/
static let __default: RDSModel.CopyOptionGroupResult = {
let defaultInstance = RDSModel.CopyOptionGroupResult(
optionGroup: nil)
return defaultInstance
}()
}
public extension CopyOptionGroupResultForCopyOptionGroup {
/**
Default instance of the CopyOptionGroupResultForCopyOptionGroup structure.
*/
static let __default: RDSModel.CopyOptionGroupResultForCopyOptionGroup = {
let defaultInstance = RDSModel.CopyOptionGroupResultForCopyOptionGroup(
copyOptionGroupResult: CopyOptionGroupResult.__default)
return defaultInstance
}()
}
public extension CreateCustomAvailabilityZoneMessage {
/**
Default instance of the CreateCustomAvailabilityZoneMessage structure.
*/
static let __default: RDSModel.CreateCustomAvailabilityZoneMessage = {
let defaultInstance = RDSModel.CreateCustomAvailabilityZoneMessage(
customAvailabilityZoneName: "value",
existingVpnId: nil,
newVpnTunnelName: nil,
vpnTunnelOriginatorIP: nil)
return defaultInstance
}()
}
public extension CreateCustomAvailabilityZoneResult {
/**
Default instance of the CreateCustomAvailabilityZoneResult structure.
*/
static let __default: RDSModel.CreateCustomAvailabilityZoneResult = {
let defaultInstance = RDSModel.CreateCustomAvailabilityZoneResult(
customAvailabilityZone: nil)
return defaultInstance
}()
}
public extension CreateCustomAvailabilityZoneResultForCreateCustomAvailabilityZone {
/**
Default instance of the CreateCustomAvailabilityZoneResultForCreateCustomAvailabilityZone structure.
*/
static let __default: RDSModel.CreateCustomAvailabilityZoneResultForCreateCustomAvailabilityZone = {
let defaultInstance = RDSModel.CreateCustomAvailabilityZoneResultForCreateCustomAvailabilityZone(
createCustomAvailabilityZoneResult: CreateCustomAvailabilityZoneResult.__default)
return defaultInstance
}()
}
public extension CreateDBClusterEndpointMessage {
/**
Default instance of the CreateDBClusterEndpointMessage structure.
*/
static let __default: RDSModel.CreateDBClusterEndpointMessage = {
let defaultInstance = RDSModel.CreateDBClusterEndpointMessage(
dBClusterEndpointIdentifier: "value",
dBClusterIdentifier: "value",
endpointType: "value",
excludedMembers: nil,
staticMembers: nil,
tags: nil)
return defaultInstance
}()
}
public extension CreateDBClusterMessage {
/**
Default instance of the CreateDBClusterMessage structure.
*/
static let __default: RDSModel.CreateDBClusterMessage = {
let defaultInstance = RDSModel.CreateDBClusterMessage(
availabilityZones: nil,
backtrackWindow: nil,
backupRetentionPeriod: nil,
characterSetName: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: "value",
dBClusterParameterGroupName: nil,
dBSubnetGroupName: nil,
databaseName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableGlobalWriteForwarding: nil,
enableHttpEndpoint: nil,
enableIAMDatabaseAuthentication: nil,
engine: "value",
engineMode: nil,
engineVersion: nil,
globalClusterIdentifier: nil,
kmsKeyId: nil,
masterUserPassword: nil,
masterUsername: nil,
optionGroupName: nil,
port: nil,
preSignedUrl: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
replicationSourceIdentifier: nil,
scalingConfiguration: nil,
storageEncrypted: nil,
tags: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension CreateDBClusterParameterGroupMessage {
/**
Default instance of the CreateDBClusterParameterGroupMessage structure.
*/
static let __default: RDSModel.CreateDBClusterParameterGroupMessage = {
let defaultInstance = RDSModel.CreateDBClusterParameterGroupMessage(
dBClusterParameterGroupName: "value",
dBParameterGroupFamily: "value",
description: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateDBClusterParameterGroupResult {
/**
Default instance of the CreateDBClusterParameterGroupResult structure.
*/
static let __default: RDSModel.CreateDBClusterParameterGroupResult = {
let defaultInstance = RDSModel.CreateDBClusterParameterGroupResult(
dBClusterParameterGroup: nil)
return defaultInstance
}()
}
public extension CreateDBClusterParameterGroupResultForCreateDBClusterParameterGroup {
/**
Default instance of the CreateDBClusterParameterGroupResultForCreateDBClusterParameterGroup structure.
*/
static let __default: RDSModel.CreateDBClusterParameterGroupResultForCreateDBClusterParameterGroup = {
let defaultInstance = RDSModel.CreateDBClusterParameterGroupResultForCreateDBClusterParameterGroup(
createDBClusterParameterGroupResult: CreateDBClusterParameterGroupResult.__default)
return defaultInstance
}()
}
public extension CreateDBClusterResult {
/**
Default instance of the CreateDBClusterResult structure.
*/
static let __default: RDSModel.CreateDBClusterResult = {
let defaultInstance = RDSModel.CreateDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension CreateDBClusterResultForCreateDBCluster {
/**
Default instance of the CreateDBClusterResultForCreateDBCluster structure.
*/
static let __default: RDSModel.CreateDBClusterResultForCreateDBCluster = {
let defaultInstance = RDSModel.CreateDBClusterResultForCreateDBCluster(
createDBClusterResult: CreateDBClusterResult.__default)
return defaultInstance
}()
}
public extension CreateDBClusterSnapshotMessage {
/**
Default instance of the CreateDBClusterSnapshotMessage structure.
*/
static let __default: RDSModel.CreateDBClusterSnapshotMessage = {
let defaultInstance = RDSModel.CreateDBClusterSnapshotMessage(
dBClusterIdentifier: "value",
dBClusterSnapshotIdentifier: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateDBClusterSnapshotResult {
/**
Default instance of the CreateDBClusterSnapshotResult structure.
*/
static let __default: RDSModel.CreateDBClusterSnapshotResult = {
let defaultInstance = RDSModel.CreateDBClusterSnapshotResult(
dBClusterSnapshot: nil)
return defaultInstance
}()
}
public extension CreateDBClusterSnapshotResultForCreateDBClusterSnapshot {
/**
Default instance of the CreateDBClusterSnapshotResultForCreateDBClusterSnapshot structure.
*/
static let __default: RDSModel.CreateDBClusterSnapshotResultForCreateDBClusterSnapshot = {
let defaultInstance = RDSModel.CreateDBClusterSnapshotResultForCreateDBClusterSnapshot(
createDBClusterSnapshotResult: CreateDBClusterSnapshotResult.__default)
return defaultInstance
}()
}
public extension CreateDBInstanceMessage {
/**
Default instance of the CreateDBInstanceMessage structure.
*/
static let __default: RDSModel.CreateDBInstanceMessage = {
let defaultInstance = RDSModel.CreateDBInstanceMessage(
allocatedStorage: nil,
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
backupRetentionPeriod: nil,
characterSetName: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: nil,
dBInstanceClass: "value",
dBInstanceIdentifier: "value",
dBName: nil,
dBParameterGroupName: nil,
dBSecurityGroups: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
enablePerformanceInsights: nil,
engine: "value",
engineVersion: nil,
iops: nil,
kmsKeyId: nil,
licenseModel: nil,
masterUserPassword: nil,
masterUsername: nil,
maxAllocatedStorage: nil,
monitoringInterval: nil,
monitoringRoleArn: nil,
multiAZ: nil,
ncharCharacterSetName: nil,
optionGroupName: nil,
performanceInsightsKMSKeyId: nil,
performanceInsightsRetentionPeriod: nil,
port: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
processorFeatures: nil,
promotionTier: nil,
publiclyAccessible: nil,
storageEncrypted: nil,
storageType: nil,
tags: nil,
tdeCredentialArn: nil,
tdeCredentialPassword: nil,
timezone: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension CreateDBInstanceReadReplicaMessage {
/**
Default instance of the CreateDBInstanceReadReplicaMessage structure.
*/
static let __default: RDSModel.CreateDBInstanceReadReplicaMessage = {
let defaultInstance = RDSModel.CreateDBInstanceReadReplicaMessage(
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
copyTagsToSnapshot: nil,
dBInstanceClass: nil,
dBInstanceIdentifier: "value",
dBParameterGroupName: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
enablePerformanceInsights: nil,
iops: nil,
kmsKeyId: nil,
maxAllocatedStorage: nil,
monitoringInterval: nil,
monitoringRoleArn: nil,
multiAZ: nil,
optionGroupName: nil,
performanceInsightsKMSKeyId: nil,
performanceInsightsRetentionPeriod: nil,
port: nil,
preSignedUrl: nil,
processorFeatures: nil,
publiclyAccessible: nil,
replicaMode: nil,
sourceDBInstanceIdentifier: "value",
storageType: nil,
tags: nil,
useDefaultProcessorFeatures: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension CreateDBInstanceReadReplicaResult {
/**
Default instance of the CreateDBInstanceReadReplicaResult structure.
*/
static let __default: RDSModel.CreateDBInstanceReadReplicaResult = {
let defaultInstance = RDSModel.CreateDBInstanceReadReplicaResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension CreateDBInstanceReadReplicaResultForCreateDBInstanceReadReplica {
/**
Default instance of the CreateDBInstanceReadReplicaResultForCreateDBInstanceReadReplica structure.
*/
static let __default: RDSModel.CreateDBInstanceReadReplicaResultForCreateDBInstanceReadReplica = {
let defaultInstance = RDSModel.CreateDBInstanceReadReplicaResultForCreateDBInstanceReadReplica(
createDBInstanceReadReplicaResult: CreateDBInstanceReadReplicaResult.__default)
return defaultInstance
}()
}
public extension CreateDBInstanceResult {
/**
Default instance of the CreateDBInstanceResult structure.
*/
static let __default: RDSModel.CreateDBInstanceResult = {
let defaultInstance = RDSModel.CreateDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension CreateDBInstanceResultForCreateDBInstance {
/**
Default instance of the CreateDBInstanceResultForCreateDBInstance structure.
*/
static let __default: RDSModel.CreateDBInstanceResultForCreateDBInstance = {
let defaultInstance = RDSModel.CreateDBInstanceResultForCreateDBInstance(
createDBInstanceResult: CreateDBInstanceResult.__default)
return defaultInstance
}()
}
public extension CreateDBParameterGroupMessage {
/**
Default instance of the CreateDBParameterGroupMessage structure.
*/
static let __default: RDSModel.CreateDBParameterGroupMessage = {
let defaultInstance = RDSModel.CreateDBParameterGroupMessage(
dBParameterGroupFamily: "value",
dBParameterGroupName: "value",
description: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateDBParameterGroupResult {
/**
Default instance of the CreateDBParameterGroupResult structure.
*/
static let __default: RDSModel.CreateDBParameterGroupResult = {
let defaultInstance = RDSModel.CreateDBParameterGroupResult(
dBParameterGroup: nil)
return defaultInstance
}()
}
public extension CreateDBParameterGroupResultForCreateDBParameterGroup {
/**
Default instance of the CreateDBParameterGroupResultForCreateDBParameterGroup structure.
*/
static let __default: RDSModel.CreateDBParameterGroupResultForCreateDBParameterGroup = {
let defaultInstance = RDSModel.CreateDBParameterGroupResultForCreateDBParameterGroup(
createDBParameterGroupResult: CreateDBParameterGroupResult.__default)
return defaultInstance
}()
}
public extension CreateDBProxyRequest {
/**
Default instance of the CreateDBProxyRequest structure.
*/
static let __default: RDSModel.CreateDBProxyRequest = {
let defaultInstance = RDSModel.CreateDBProxyRequest(
auth: [],
dBProxyName: "value",
debugLogging: nil,
engineFamily: .__default,
idleClientTimeout: nil,
requireTLS: nil,
roleArn: "value",
tags: nil,
vpcSecurityGroupIds: nil,
vpcSubnetIds: [])
return defaultInstance
}()
}
public extension CreateDBProxyResponse {
/**
Default instance of the CreateDBProxyResponse structure.
*/
static let __default: RDSModel.CreateDBProxyResponse = {
let defaultInstance = RDSModel.CreateDBProxyResponse(
dBProxy: nil)
return defaultInstance
}()
}
public extension CreateDBProxyResponseForCreateDBProxy {
/**
Default instance of the CreateDBProxyResponseForCreateDBProxy structure.
*/
static let __default: RDSModel.CreateDBProxyResponseForCreateDBProxy = {
let defaultInstance = RDSModel.CreateDBProxyResponseForCreateDBProxy(
createDBProxyResult: CreateDBProxyResponse.__default)
return defaultInstance
}()
}
public extension CreateDBSecurityGroupMessage {
/**
Default instance of the CreateDBSecurityGroupMessage structure.
*/
static let __default: RDSModel.CreateDBSecurityGroupMessage = {
let defaultInstance = RDSModel.CreateDBSecurityGroupMessage(
dBSecurityGroupDescription: "value",
dBSecurityGroupName: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateDBSecurityGroupResult {
/**
Default instance of the CreateDBSecurityGroupResult structure.
*/
static let __default: RDSModel.CreateDBSecurityGroupResult = {
let defaultInstance = RDSModel.CreateDBSecurityGroupResult(
dBSecurityGroup: nil)
return defaultInstance
}()
}
public extension CreateDBSecurityGroupResultForCreateDBSecurityGroup {
/**
Default instance of the CreateDBSecurityGroupResultForCreateDBSecurityGroup structure.
*/
static let __default: RDSModel.CreateDBSecurityGroupResultForCreateDBSecurityGroup = {
let defaultInstance = RDSModel.CreateDBSecurityGroupResultForCreateDBSecurityGroup(
createDBSecurityGroupResult: CreateDBSecurityGroupResult.__default)
return defaultInstance
}()
}
public extension CreateDBSnapshotMessage {
/**
Default instance of the CreateDBSnapshotMessage structure.
*/
static let __default: RDSModel.CreateDBSnapshotMessage = {
let defaultInstance = RDSModel.CreateDBSnapshotMessage(
dBInstanceIdentifier: "value",
dBSnapshotIdentifier: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateDBSnapshotResult {
/**
Default instance of the CreateDBSnapshotResult structure.
*/
static let __default: RDSModel.CreateDBSnapshotResult = {
let defaultInstance = RDSModel.CreateDBSnapshotResult(
dBSnapshot: nil)
return defaultInstance
}()
}
public extension CreateDBSnapshotResultForCreateDBSnapshot {
/**
Default instance of the CreateDBSnapshotResultForCreateDBSnapshot structure.
*/
static let __default: RDSModel.CreateDBSnapshotResultForCreateDBSnapshot = {
let defaultInstance = RDSModel.CreateDBSnapshotResultForCreateDBSnapshot(
createDBSnapshotResult: CreateDBSnapshotResult.__default)
return defaultInstance
}()
}
public extension CreateDBSubnetGroupMessage {
/**
Default instance of the CreateDBSubnetGroupMessage structure.
*/
static let __default: RDSModel.CreateDBSubnetGroupMessage = {
let defaultInstance = RDSModel.CreateDBSubnetGroupMessage(
dBSubnetGroupDescription: "value",
dBSubnetGroupName: "value",
subnetIds: [],
tags: nil)
return defaultInstance
}()
}
public extension CreateDBSubnetGroupResult {
/**
Default instance of the CreateDBSubnetGroupResult structure.
*/
static let __default: RDSModel.CreateDBSubnetGroupResult = {
let defaultInstance = RDSModel.CreateDBSubnetGroupResult(
dBSubnetGroup: nil)
return defaultInstance
}()
}
public extension CreateDBSubnetGroupResultForCreateDBSubnetGroup {
/**
Default instance of the CreateDBSubnetGroupResultForCreateDBSubnetGroup structure.
*/
static let __default: RDSModel.CreateDBSubnetGroupResultForCreateDBSubnetGroup = {
let defaultInstance = RDSModel.CreateDBSubnetGroupResultForCreateDBSubnetGroup(
createDBSubnetGroupResult: CreateDBSubnetGroupResult.__default)
return defaultInstance
}()
}
public extension CreateEventSubscriptionMessage {
/**
Default instance of the CreateEventSubscriptionMessage structure.
*/
static let __default: RDSModel.CreateEventSubscriptionMessage = {
let defaultInstance = RDSModel.CreateEventSubscriptionMessage(
enabled: nil,
eventCategories: nil,
snsTopicArn: "value",
sourceIds: nil,
sourceType: nil,
subscriptionName: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateEventSubscriptionResult {
/**
Default instance of the CreateEventSubscriptionResult structure.
*/
static let __default: RDSModel.CreateEventSubscriptionResult = {
let defaultInstance = RDSModel.CreateEventSubscriptionResult(
eventSubscription: nil)
return defaultInstance
}()
}
public extension CreateEventSubscriptionResultForCreateEventSubscription {
/**
Default instance of the CreateEventSubscriptionResultForCreateEventSubscription structure.
*/
static let __default: RDSModel.CreateEventSubscriptionResultForCreateEventSubscription = {
let defaultInstance = RDSModel.CreateEventSubscriptionResultForCreateEventSubscription(
createEventSubscriptionResult: CreateEventSubscriptionResult.__default)
return defaultInstance
}()
}
public extension CreateGlobalClusterMessage {
/**
Default instance of the CreateGlobalClusterMessage structure.
*/
static let __default: RDSModel.CreateGlobalClusterMessage = {
let defaultInstance = RDSModel.CreateGlobalClusterMessage(
databaseName: nil,
deletionProtection: nil,
engine: nil,
engineVersion: nil,
globalClusterIdentifier: nil,
sourceDBClusterIdentifier: nil,
storageEncrypted: nil)
return defaultInstance
}()
}
public extension CreateGlobalClusterResult {
/**
Default instance of the CreateGlobalClusterResult structure.
*/
static let __default: RDSModel.CreateGlobalClusterResult = {
let defaultInstance = RDSModel.CreateGlobalClusterResult(
globalCluster: nil)
return defaultInstance
}()
}
public extension CreateGlobalClusterResultForCreateGlobalCluster {
/**
Default instance of the CreateGlobalClusterResultForCreateGlobalCluster structure.
*/
static let __default: RDSModel.CreateGlobalClusterResultForCreateGlobalCluster = {
let defaultInstance = RDSModel.CreateGlobalClusterResultForCreateGlobalCluster(
createGlobalClusterResult: CreateGlobalClusterResult.__default)
return defaultInstance
}()
}
public extension CreateOptionGroupMessage {
/**
Default instance of the CreateOptionGroupMessage structure.
*/
static let __default: RDSModel.CreateOptionGroupMessage = {
let defaultInstance = RDSModel.CreateOptionGroupMessage(
engineName: "value",
majorEngineVersion: "value",
optionGroupDescription: "value",
optionGroupName: "value",
tags: nil)
return defaultInstance
}()
}
public extension CreateOptionGroupResult {
/**
Default instance of the CreateOptionGroupResult structure.
*/
static let __default: RDSModel.CreateOptionGroupResult = {
let defaultInstance = RDSModel.CreateOptionGroupResult(
optionGroup: nil)
return defaultInstance
}()
}
public extension CreateOptionGroupResultForCreateOptionGroup {
/**
Default instance of the CreateOptionGroupResultForCreateOptionGroup structure.
*/
static let __default: RDSModel.CreateOptionGroupResultForCreateOptionGroup = {
let defaultInstance = RDSModel.CreateOptionGroupResultForCreateOptionGroup(
createOptionGroupResult: CreateOptionGroupResult.__default)
return defaultInstance
}()
}
public extension CustomAvailabilityZone {
/**
Default instance of the CustomAvailabilityZone structure.
*/
static let __default: RDSModel.CustomAvailabilityZone = {
let defaultInstance = RDSModel.CustomAvailabilityZone(
customAvailabilityZoneId: nil,
customAvailabilityZoneName: nil,
customAvailabilityZoneStatus: nil,
vpnDetails: nil)
return defaultInstance
}()
}
public extension CustomAvailabilityZoneAlreadyExistsFault {
/**
Default instance of the CustomAvailabilityZoneAlreadyExistsFault structure.
*/
static let __default: RDSModel.CustomAvailabilityZoneAlreadyExistsFault = {
let defaultInstance = RDSModel.CustomAvailabilityZoneAlreadyExistsFault()
return defaultInstance
}()
}
public extension CustomAvailabilityZoneMessage {
/**
Default instance of the CustomAvailabilityZoneMessage structure.
*/
static let __default: RDSModel.CustomAvailabilityZoneMessage = {
let defaultInstance = RDSModel.CustomAvailabilityZoneMessage(
customAvailabilityZones: nil,
marker: nil)
return defaultInstance
}()
}
public extension CustomAvailabilityZoneMessageForDescribeCustomAvailabilityZones {
/**
Default instance of the CustomAvailabilityZoneMessageForDescribeCustomAvailabilityZones structure.
*/
static let __default: RDSModel.CustomAvailabilityZoneMessageForDescribeCustomAvailabilityZones = {
let defaultInstance = RDSModel.CustomAvailabilityZoneMessageForDescribeCustomAvailabilityZones(
describeCustomAvailabilityZonesResult: CustomAvailabilityZoneMessage.__default)
return defaultInstance
}()
}
public extension CustomAvailabilityZoneNotFoundFault {
/**
Default instance of the CustomAvailabilityZoneNotFoundFault structure.
*/
static let __default: RDSModel.CustomAvailabilityZoneNotFoundFault = {
let defaultInstance = RDSModel.CustomAvailabilityZoneNotFoundFault()
return defaultInstance
}()
}
public extension CustomAvailabilityZoneQuotaExceededFault {
/**
Default instance of the CustomAvailabilityZoneQuotaExceededFault structure.
*/
static let __default: RDSModel.CustomAvailabilityZoneQuotaExceededFault = {
let defaultInstance = RDSModel.CustomAvailabilityZoneQuotaExceededFault()
return defaultInstance
}()
}
public extension DBCluster {
/**
Default instance of the DBCluster structure.
*/
static let __default: RDSModel.DBCluster = {
let defaultInstance = RDSModel.DBCluster(
activityStreamKinesisStreamName: nil,
activityStreamKmsKeyId: nil,
activityStreamMode: nil,
activityStreamStatus: nil,
allocatedStorage: nil,
associatedRoles: nil,
availabilityZones: nil,
backtrackConsumedChangeRecords: nil,
backtrackWindow: nil,
backupRetentionPeriod: nil,
capacity: nil,
characterSetName: nil,
cloneGroupId: nil,
clusterCreateTime: nil,
copyTagsToSnapshot: nil,
crossAccountClone: nil,
customEndpoints: nil,
dBClusterArn: nil,
dBClusterIdentifier: nil,
dBClusterMembers: nil,
dBClusterOptionGroupMemberships: nil,
dBClusterParameterGroup: nil,
dBSubnetGroup: nil,
databaseName: nil,
dbClusterResourceId: nil,
deletionProtection: nil,
domainMemberships: nil,
earliestBacktrackTime: nil,
earliestRestorableTime: nil,
enabledCloudwatchLogsExports: nil,
endpoint: nil,
engine: nil,
engineMode: nil,
engineVersion: nil,
globalWriteForwardingRequested: nil,
globalWriteForwardingStatus: nil,
hostedZoneId: nil,
httpEndpointEnabled: nil,
iAMDatabaseAuthenticationEnabled: nil,
kmsKeyId: nil,
latestRestorableTime: nil,
masterUsername: nil,
multiAZ: nil,
percentProgress: nil,
port: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
readReplicaIdentifiers: nil,
readerEndpoint: nil,
replicationSourceIdentifier: nil,
scalingConfigurationInfo: nil,
status: nil,
storageEncrypted: nil,
tagList: nil,
vpcSecurityGroups: nil)
return defaultInstance
}()
}
public extension DBClusterAlreadyExistsFault {
/**
Default instance of the DBClusterAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBClusterAlreadyExistsFault = {
let defaultInstance = RDSModel.DBClusterAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBClusterBacktrack {
/**
Default instance of the DBClusterBacktrack structure.
*/
static let __default: RDSModel.DBClusterBacktrack = {
let defaultInstance = RDSModel.DBClusterBacktrack(
backtrackIdentifier: nil,
backtrackRequestCreationTime: nil,
backtrackTo: nil,
backtrackedFrom: nil,
dBClusterIdentifier: nil,
status: nil)
return defaultInstance
}()
}
public extension DBClusterBacktrackForBacktrackDBCluster {
/**
Default instance of the DBClusterBacktrackForBacktrackDBCluster structure.
*/
static let __default: RDSModel.DBClusterBacktrackForBacktrackDBCluster = {
let defaultInstance = RDSModel.DBClusterBacktrackForBacktrackDBCluster(
backtrackDBClusterResult: DBClusterBacktrack.__default)
return defaultInstance
}()
}
public extension DBClusterBacktrackMessage {
/**
Default instance of the DBClusterBacktrackMessage structure.
*/
static let __default: RDSModel.DBClusterBacktrackMessage = {
let defaultInstance = RDSModel.DBClusterBacktrackMessage(
dBClusterBacktracks: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBClusterBacktrackMessageForDescribeDBClusterBacktracks {
/**
Default instance of the DBClusterBacktrackMessageForDescribeDBClusterBacktracks structure.
*/
static let __default: RDSModel.DBClusterBacktrackMessageForDescribeDBClusterBacktracks = {
let defaultInstance = RDSModel.DBClusterBacktrackMessageForDescribeDBClusterBacktracks(
describeDBClusterBacktracksResult: DBClusterBacktrackMessage.__default)
return defaultInstance
}()
}
public extension DBClusterBacktrackNotFoundFault {
/**
Default instance of the DBClusterBacktrackNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterBacktrackNotFoundFault = {
let defaultInstance = RDSModel.DBClusterBacktrackNotFoundFault()
return defaultInstance
}()
}
public extension DBClusterCapacityInfo {
/**
Default instance of the DBClusterCapacityInfo structure.
*/
static let __default: RDSModel.DBClusterCapacityInfo = {
let defaultInstance = RDSModel.DBClusterCapacityInfo(
currentCapacity: nil,
dBClusterIdentifier: nil,
pendingCapacity: nil,
secondsBeforeTimeout: nil,
timeoutAction: nil)
return defaultInstance
}()
}
public extension DBClusterCapacityInfoForModifyCurrentDBClusterCapacity {
/**
Default instance of the DBClusterCapacityInfoForModifyCurrentDBClusterCapacity structure.
*/
static let __default: RDSModel.DBClusterCapacityInfoForModifyCurrentDBClusterCapacity = {
let defaultInstance = RDSModel.DBClusterCapacityInfoForModifyCurrentDBClusterCapacity(
modifyCurrentDBClusterCapacityResult: DBClusterCapacityInfo.__default)
return defaultInstance
}()
}
public extension DBClusterEndpoint {
/**
Default instance of the DBClusterEndpoint structure.
*/
static let __default: RDSModel.DBClusterEndpoint = {
let defaultInstance = RDSModel.DBClusterEndpoint(
customEndpointType: nil,
dBClusterEndpointArn: nil,
dBClusterEndpointIdentifier: nil,
dBClusterEndpointResourceIdentifier: nil,
dBClusterIdentifier: nil,
endpoint: nil,
endpointType: nil,
excludedMembers: nil,
staticMembers: nil,
status: nil)
return defaultInstance
}()
}
public extension DBClusterEndpointAlreadyExistsFault {
/**
Default instance of the DBClusterEndpointAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBClusterEndpointAlreadyExistsFault = {
let defaultInstance = RDSModel.DBClusterEndpointAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBClusterEndpointForCreateDBClusterEndpoint {
/**
Default instance of the DBClusterEndpointForCreateDBClusterEndpoint structure.
*/
static let __default: RDSModel.DBClusterEndpointForCreateDBClusterEndpoint = {
let defaultInstance = RDSModel.DBClusterEndpointForCreateDBClusterEndpoint(
createDBClusterEndpointResult: DBClusterEndpoint.__default)
return defaultInstance
}()
}
public extension DBClusterEndpointForDeleteDBClusterEndpoint {
/**
Default instance of the DBClusterEndpointForDeleteDBClusterEndpoint structure.
*/
static let __default: RDSModel.DBClusterEndpointForDeleteDBClusterEndpoint = {
let defaultInstance = RDSModel.DBClusterEndpointForDeleteDBClusterEndpoint(
deleteDBClusterEndpointResult: DBClusterEndpoint.__default)
return defaultInstance
}()
}
public extension DBClusterEndpointForModifyDBClusterEndpoint {
/**
Default instance of the DBClusterEndpointForModifyDBClusterEndpoint structure.
*/
static let __default: RDSModel.DBClusterEndpointForModifyDBClusterEndpoint = {
let defaultInstance = RDSModel.DBClusterEndpointForModifyDBClusterEndpoint(
modifyDBClusterEndpointResult: DBClusterEndpoint.__default)
return defaultInstance
}()
}
public extension DBClusterEndpointMessage {
/**
Default instance of the DBClusterEndpointMessage structure.
*/
static let __default: RDSModel.DBClusterEndpointMessage = {
let defaultInstance = RDSModel.DBClusterEndpointMessage(
dBClusterEndpoints: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBClusterEndpointMessageForDescribeDBClusterEndpoints {
/**
Default instance of the DBClusterEndpointMessageForDescribeDBClusterEndpoints structure.
*/
static let __default: RDSModel.DBClusterEndpointMessageForDescribeDBClusterEndpoints = {
let defaultInstance = RDSModel.DBClusterEndpointMessageForDescribeDBClusterEndpoints(
describeDBClusterEndpointsResult: DBClusterEndpointMessage.__default)
return defaultInstance
}()
}
public extension DBClusterEndpointNotFoundFault {
/**
Default instance of the DBClusterEndpointNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterEndpointNotFoundFault = {
let defaultInstance = RDSModel.DBClusterEndpointNotFoundFault()
return defaultInstance
}()
}
public extension DBClusterEndpointQuotaExceededFault {
/**
Default instance of the DBClusterEndpointQuotaExceededFault structure.
*/
static let __default: RDSModel.DBClusterEndpointQuotaExceededFault = {
let defaultInstance = RDSModel.DBClusterEndpointQuotaExceededFault()
return defaultInstance
}()
}
public extension DBClusterMember {
/**
Default instance of the DBClusterMember structure.
*/
static let __default: RDSModel.DBClusterMember = {
let defaultInstance = RDSModel.DBClusterMember(
dBClusterParameterGroupStatus: nil,
dBInstanceIdentifier: nil,
isClusterWriter: nil,
promotionTier: nil)
return defaultInstance
}()
}
public extension DBClusterMessage {
/**
Default instance of the DBClusterMessage structure.
*/
static let __default: RDSModel.DBClusterMessage = {
let defaultInstance = RDSModel.DBClusterMessage(
dBClusters: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBClusterMessageForDescribeDBClusters {
/**
Default instance of the DBClusterMessageForDescribeDBClusters structure.
*/
static let __default: RDSModel.DBClusterMessageForDescribeDBClusters = {
let defaultInstance = RDSModel.DBClusterMessageForDescribeDBClusters(
describeDBClustersResult: DBClusterMessage.__default)
return defaultInstance
}()
}
public extension DBClusterNotFoundFault {
/**
Default instance of the DBClusterNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterNotFoundFault = {
let defaultInstance = RDSModel.DBClusterNotFoundFault()
return defaultInstance
}()
}
public extension DBClusterOptionGroupStatus {
/**
Default instance of the DBClusterOptionGroupStatus structure.
*/
static let __default: RDSModel.DBClusterOptionGroupStatus = {
let defaultInstance = RDSModel.DBClusterOptionGroupStatus(
dBClusterOptionGroupName: nil,
status: nil)
return defaultInstance
}()
}
public extension DBClusterParameterGroup {
/**
Default instance of the DBClusterParameterGroup structure.
*/
static let __default: RDSModel.DBClusterParameterGroup = {
let defaultInstance = RDSModel.DBClusterParameterGroup(
dBClusterParameterGroupArn: nil,
dBClusterParameterGroupName: nil,
dBParameterGroupFamily: nil,
description: nil)
return defaultInstance
}()
}
public extension DBClusterParameterGroupDetails {
/**
Default instance of the DBClusterParameterGroupDetails structure.
*/
static let __default: RDSModel.DBClusterParameterGroupDetails = {
let defaultInstance = RDSModel.DBClusterParameterGroupDetails(
marker: nil,
parameters: nil)
return defaultInstance
}()
}
public extension DBClusterParameterGroupDetailsForDescribeDBClusterParameters {
/**
Default instance of the DBClusterParameterGroupDetailsForDescribeDBClusterParameters structure.
*/
static let __default: RDSModel.DBClusterParameterGroupDetailsForDescribeDBClusterParameters = {
let defaultInstance = RDSModel.DBClusterParameterGroupDetailsForDescribeDBClusterParameters(
describeDBClusterParametersResult: DBClusterParameterGroupDetails.__default)
return defaultInstance
}()
}
public extension DBClusterParameterGroupNameMessage {
/**
Default instance of the DBClusterParameterGroupNameMessage structure.
*/
static let __default: RDSModel.DBClusterParameterGroupNameMessage = {
let defaultInstance = RDSModel.DBClusterParameterGroupNameMessage(
dBClusterParameterGroupName: nil)
return defaultInstance
}()
}
public extension DBClusterParameterGroupNameMessageForModifyDBClusterParameterGroup {
/**
Default instance of the DBClusterParameterGroupNameMessageForModifyDBClusterParameterGroup structure.
*/
static let __default: RDSModel.DBClusterParameterGroupNameMessageForModifyDBClusterParameterGroup = {
let defaultInstance = RDSModel.DBClusterParameterGroupNameMessageForModifyDBClusterParameterGroup(
modifyDBClusterParameterGroupResult: DBClusterParameterGroupNameMessage.__default)
return defaultInstance
}()
}
public extension DBClusterParameterGroupNameMessageForResetDBClusterParameterGroup {
/**
Default instance of the DBClusterParameterGroupNameMessageForResetDBClusterParameterGroup structure.
*/
static let __default: RDSModel.DBClusterParameterGroupNameMessageForResetDBClusterParameterGroup = {
let defaultInstance = RDSModel.DBClusterParameterGroupNameMessageForResetDBClusterParameterGroup(
resetDBClusterParameterGroupResult: DBClusterParameterGroupNameMessage.__default)
return defaultInstance
}()
}
public extension DBClusterParameterGroupNotFoundFault {
/**
Default instance of the DBClusterParameterGroupNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterParameterGroupNotFoundFault = {
let defaultInstance = RDSModel.DBClusterParameterGroupNotFoundFault()
return defaultInstance
}()
}
public extension DBClusterParameterGroupsMessage {
/**
Default instance of the DBClusterParameterGroupsMessage structure.
*/
static let __default: RDSModel.DBClusterParameterGroupsMessage = {
let defaultInstance = RDSModel.DBClusterParameterGroupsMessage(
dBClusterParameterGroups: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBClusterParameterGroupsMessageForDescribeDBClusterParameterGroups {
/**
Default instance of the DBClusterParameterGroupsMessageForDescribeDBClusterParameterGroups structure.
*/
static let __default: RDSModel.DBClusterParameterGroupsMessageForDescribeDBClusterParameterGroups = {
let defaultInstance = RDSModel.DBClusterParameterGroupsMessageForDescribeDBClusterParameterGroups(
describeDBClusterParameterGroupsResult: DBClusterParameterGroupsMessage.__default)
return defaultInstance
}()
}
public extension DBClusterQuotaExceededFault {
/**
Default instance of the DBClusterQuotaExceededFault structure.
*/
static let __default: RDSModel.DBClusterQuotaExceededFault = {
let defaultInstance = RDSModel.DBClusterQuotaExceededFault()
return defaultInstance
}()
}
public extension DBClusterRole {
/**
Default instance of the DBClusterRole structure.
*/
static let __default: RDSModel.DBClusterRole = {
let defaultInstance = RDSModel.DBClusterRole(
featureName: nil,
roleArn: nil,
status: nil)
return defaultInstance
}()
}
public extension DBClusterRoleAlreadyExistsFault {
/**
Default instance of the DBClusterRoleAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBClusterRoleAlreadyExistsFault = {
let defaultInstance = RDSModel.DBClusterRoleAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBClusterRoleNotFoundFault {
/**
Default instance of the DBClusterRoleNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterRoleNotFoundFault = {
let defaultInstance = RDSModel.DBClusterRoleNotFoundFault()
return defaultInstance
}()
}
public extension DBClusterRoleQuotaExceededFault {
/**
Default instance of the DBClusterRoleQuotaExceededFault structure.
*/
static let __default: RDSModel.DBClusterRoleQuotaExceededFault = {
let defaultInstance = RDSModel.DBClusterRoleQuotaExceededFault()
return defaultInstance
}()
}
public extension DBClusterSnapshot {
/**
Default instance of the DBClusterSnapshot structure.
*/
static let __default: RDSModel.DBClusterSnapshot = {
let defaultInstance = RDSModel.DBClusterSnapshot(
allocatedStorage: nil,
availabilityZones: nil,
clusterCreateTime: nil,
dBClusterIdentifier: nil,
dBClusterSnapshotArn: nil,
dBClusterSnapshotIdentifier: nil,
engine: nil,
engineVersion: nil,
iAMDatabaseAuthenticationEnabled: nil,
kmsKeyId: nil,
licenseModel: nil,
masterUsername: nil,
percentProgress: nil,
port: nil,
snapshotCreateTime: nil,
snapshotType: nil,
sourceDBClusterSnapshotArn: nil,
status: nil,
storageEncrypted: nil,
tagList: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension DBClusterSnapshotAlreadyExistsFault {
/**
Default instance of the DBClusterSnapshotAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBClusterSnapshotAlreadyExistsFault = {
let defaultInstance = RDSModel.DBClusterSnapshotAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBClusterSnapshotAttribute {
/**
Default instance of the DBClusterSnapshotAttribute structure.
*/
static let __default: RDSModel.DBClusterSnapshotAttribute = {
let defaultInstance = RDSModel.DBClusterSnapshotAttribute(
attributeName: nil,
attributeValues: nil)
return defaultInstance
}()
}
public extension DBClusterSnapshotAttributesResult {
/**
Default instance of the DBClusterSnapshotAttributesResult structure.
*/
static let __default: RDSModel.DBClusterSnapshotAttributesResult = {
let defaultInstance = RDSModel.DBClusterSnapshotAttributesResult(
dBClusterSnapshotAttributes: nil,
dBClusterSnapshotIdentifier: nil)
return defaultInstance
}()
}
public extension DBClusterSnapshotMessage {
/**
Default instance of the DBClusterSnapshotMessage structure.
*/
static let __default: RDSModel.DBClusterSnapshotMessage = {
let defaultInstance = RDSModel.DBClusterSnapshotMessage(
dBClusterSnapshots: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBClusterSnapshotMessageForDescribeDBClusterSnapshots {
/**
Default instance of the DBClusterSnapshotMessageForDescribeDBClusterSnapshots structure.
*/
static let __default: RDSModel.DBClusterSnapshotMessageForDescribeDBClusterSnapshots = {
let defaultInstance = RDSModel.DBClusterSnapshotMessageForDescribeDBClusterSnapshots(
describeDBClusterSnapshotsResult: DBClusterSnapshotMessage.__default)
return defaultInstance
}()
}
public extension DBClusterSnapshotNotFoundFault {
/**
Default instance of the DBClusterSnapshotNotFoundFault structure.
*/
static let __default: RDSModel.DBClusterSnapshotNotFoundFault = {
let defaultInstance = RDSModel.DBClusterSnapshotNotFoundFault()
return defaultInstance
}()
}
public extension DBEngineVersion {
/**
Default instance of the DBEngineVersion structure.
*/
static let __default: RDSModel.DBEngineVersion = {
let defaultInstance = RDSModel.DBEngineVersion(
dBEngineDescription: nil,
dBEngineVersionDescription: nil,
dBParameterGroupFamily: nil,
defaultCharacterSet: nil,
engine: nil,
engineVersion: nil,
exportableLogTypes: nil,
status: nil,
supportedCharacterSets: nil,
supportedEngineModes: nil,
supportedFeatureNames: nil,
supportedNcharCharacterSets: nil,
supportedTimezones: nil,
supportsGlobalDatabases: nil,
supportsLogExportsToCloudwatchLogs: nil,
supportsParallelQuery: nil,
supportsReadReplica: nil,
validUpgradeTarget: nil)
return defaultInstance
}()
}
public extension DBEngineVersionMessage {
/**
Default instance of the DBEngineVersionMessage structure.
*/
static let __default: RDSModel.DBEngineVersionMessage = {
let defaultInstance = RDSModel.DBEngineVersionMessage(
dBEngineVersions: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBEngineVersionMessageForDescribeDBEngineVersions {
/**
Default instance of the DBEngineVersionMessageForDescribeDBEngineVersions structure.
*/
static let __default: RDSModel.DBEngineVersionMessageForDescribeDBEngineVersions = {
let defaultInstance = RDSModel.DBEngineVersionMessageForDescribeDBEngineVersions(
describeDBEngineVersionsResult: DBEngineVersionMessage.__default)
return defaultInstance
}()
}
public extension DBInstance {
/**
Default instance of the DBInstance structure.
*/
static let __default: RDSModel.DBInstance = {
let defaultInstance = RDSModel.DBInstance(
allocatedStorage: nil,
associatedRoles: nil,
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
backupRetentionPeriod: nil,
cACertificateIdentifier: nil,
characterSetName: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: nil,
dBInstanceArn: nil,
dBInstanceClass: nil,
dBInstanceIdentifier: nil,
dBInstanceStatus: nil,
dBName: nil,
dBParameterGroups: nil,
dBSecurityGroups: nil,
dBSubnetGroup: nil,
dbInstancePort: nil,
dbiResourceId: nil,
deletionProtection: nil,
domainMemberships: nil,
enabledCloudwatchLogsExports: nil,
endpoint: nil,
engine: nil,
engineVersion: nil,
enhancedMonitoringResourceArn: nil,
iAMDatabaseAuthenticationEnabled: nil,
instanceCreateTime: nil,
iops: nil,
kmsKeyId: nil,
latestRestorableTime: nil,
licenseModel: nil,
listenerEndpoint: nil,
masterUsername: nil,
maxAllocatedStorage: nil,
monitoringInterval: nil,
monitoringRoleArn: nil,
multiAZ: nil,
ncharCharacterSetName: nil,
optionGroupMemberships: nil,
pendingModifiedValues: nil,
performanceInsightsEnabled: nil,
performanceInsightsKMSKeyId: nil,
performanceInsightsRetentionPeriod: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
processorFeatures: nil,
promotionTier: nil,
publiclyAccessible: nil,
readReplicaDBClusterIdentifiers: nil,
readReplicaDBInstanceIdentifiers: nil,
readReplicaSourceDBInstanceIdentifier: nil,
replicaMode: nil,
secondaryAvailabilityZone: nil,
statusInfos: nil,
storageEncrypted: nil,
storageType: nil,
tagList: nil,
tdeCredentialArn: nil,
timezone: nil,
vpcSecurityGroups: nil)
return defaultInstance
}()
}
public extension DBInstanceAlreadyExistsFault {
/**
Default instance of the DBInstanceAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBInstanceAlreadyExistsFault = {
let defaultInstance = RDSModel.DBInstanceAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBInstanceAutomatedBackup {
/**
Default instance of the DBInstanceAutomatedBackup structure.
*/
static let __default: RDSModel.DBInstanceAutomatedBackup = {
let defaultInstance = RDSModel.DBInstanceAutomatedBackup(
allocatedStorage: nil,
availabilityZone: nil,
dBInstanceArn: nil,
dBInstanceIdentifier: nil,
dbiResourceId: nil,
encrypted: nil,
engine: nil,
engineVersion: nil,
iAMDatabaseAuthenticationEnabled: nil,
instanceCreateTime: nil,
iops: nil,
kmsKeyId: nil,
licenseModel: nil,
masterUsername: nil,
optionGroupName: nil,
port: nil,
region: nil,
restoreWindow: nil,
status: nil,
storageType: nil,
tdeCredentialArn: nil,
timezone: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension DBInstanceAutomatedBackupMessage {
/**
Default instance of the DBInstanceAutomatedBackupMessage structure.
*/
static let __default: RDSModel.DBInstanceAutomatedBackupMessage = {
let defaultInstance = RDSModel.DBInstanceAutomatedBackupMessage(
dBInstanceAutomatedBackups: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBInstanceAutomatedBackupMessageForDescribeDBInstanceAutomatedBackups {
/**
Default instance of the DBInstanceAutomatedBackupMessageForDescribeDBInstanceAutomatedBackups structure.
*/
static let __default: RDSModel.DBInstanceAutomatedBackupMessageForDescribeDBInstanceAutomatedBackups = {
let defaultInstance = RDSModel.DBInstanceAutomatedBackupMessageForDescribeDBInstanceAutomatedBackups(
describeDBInstanceAutomatedBackupsResult: DBInstanceAutomatedBackupMessage.__default)
return defaultInstance
}()
}
public extension DBInstanceAutomatedBackupNotFoundFault {
/**
Default instance of the DBInstanceAutomatedBackupNotFoundFault structure.
*/
static let __default: RDSModel.DBInstanceAutomatedBackupNotFoundFault = {
let defaultInstance = RDSModel.DBInstanceAutomatedBackupNotFoundFault()
return defaultInstance
}()
}
public extension DBInstanceAutomatedBackupQuotaExceededFault {
/**
Default instance of the DBInstanceAutomatedBackupQuotaExceededFault structure.
*/
static let __default: RDSModel.DBInstanceAutomatedBackupQuotaExceededFault = {
let defaultInstance = RDSModel.DBInstanceAutomatedBackupQuotaExceededFault()
return defaultInstance
}()
}
public extension DBInstanceMessage {
/**
Default instance of the DBInstanceMessage structure.
*/
static let __default: RDSModel.DBInstanceMessage = {
let defaultInstance = RDSModel.DBInstanceMessage(
dBInstances: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBInstanceMessageForDescribeDBInstances {
/**
Default instance of the DBInstanceMessageForDescribeDBInstances structure.
*/
static let __default: RDSModel.DBInstanceMessageForDescribeDBInstances = {
let defaultInstance = RDSModel.DBInstanceMessageForDescribeDBInstances(
describeDBInstancesResult: DBInstanceMessage.__default)
return defaultInstance
}()
}
public extension DBInstanceNotFoundFault {
/**
Default instance of the DBInstanceNotFoundFault structure.
*/
static let __default: RDSModel.DBInstanceNotFoundFault = {
let defaultInstance = RDSModel.DBInstanceNotFoundFault()
return defaultInstance
}()
}
public extension DBInstanceRole {
/**
Default instance of the DBInstanceRole structure.
*/
static let __default: RDSModel.DBInstanceRole = {
let defaultInstance = RDSModel.DBInstanceRole(
featureName: nil,
roleArn: nil,
status: nil)
return defaultInstance
}()
}
public extension DBInstanceRoleAlreadyExistsFault {
/**
Default instance of the DBInstanceRoleAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBInstanceRoleAlreadyExistsFault = {
let defaultInstance = RDSModel.DBInstanceRoleAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBInstanceRoleNotFoundFault {
/**
Default instance of the DBInstanceRoleNotFoundFault structure.
*/
static let __default: RDSModel.DBInstanceRoleNotFoundFault = {
let defaultInstance = RDSModel.DBInstanceRoleNotFoundFault()
return defaultInstance
}()
}
public extension DBInstanceRoleQuotaExceededFault {
/**
Default instance of the DBInstanceRoleQuotaExceededFault structure.
*/
static let __default: RDSModel.DBInstanceRoleQuotaExceededFault = {
let defaultInstance = RDSModel.DBInstanceRoleQuotaExceededFault()
return defaultInstance
}()
}
public extension DBInstanceStatusInfo {
/**
Default instance of the DBInstanceStatusInfo structure.
*/
static let __default: RDSModel.DBInstanceStatusInfo = {
let defaultInstance = RDSModel.DBInstanceStatusInfo(
message: nil,
normal: nil,
status: nil,
statusType: nil)
return defaultInstance
}()
}
public extension DBLogFileNotFoundFault {
/**
Default instance of the DBLogFileNotFoundFault structure.
*/
static let __default: RDSModel.DBLogFileNotFoundFault = {
let defaultInstance = RDSModel.DBLogFileNotFoundFault()
return defaultInstance
}()
}
public extension DBParameterGroup {
/**
Default instance of the DBParameterGroup structure.
*/
static let __default: RDSModel.DBParameterGroup = {
let defaultInstance = RDSModel.DBParameterGroup(
dBParameterGroupArn: nil,
dBParameterGroupFamily: nil,
dBParameterGroupName: nil,
description: nil)
return defaultInstance
}()
}
public extension DBParameterGroupAlreadyExistsFault {
/**
Default instance of the DBParameterGroupAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBParameterGroupAlreadyExistsFault = {
let defaultInstance = RDSModel.DBParameterGroupAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBParameterGroupDetails {
/**
Default instance of the DBParameterGroupDetails structure.
*/
static let __default: RDSModel.DBParameterGroupDetails = {
let defaultInstance = RDSModel.DBParameterGroupDetails(
marker: nil,
parameters: nil)
return defaultInstance
}()
}
public extension DBParameterGroupDetailsForDescribeDBParameters {
/**
Default instance of the DBParameterGroupDetailsForDescribeDBParameters structure.
*/
static let __default: RDSModel.DBParameterGroupDetailsForDescribeDBParameters = {
let defaultInstance = RDSModel.DBParameterGroupDetailsForDescribeDBParameters(
describeDBParametersResult: DBParameterGroupDetails.__default)
return defaultInstance
}()
}
public extension DBParameterGroupNameMessage {
/**
Default instance of the DBParameterGroupNameMessage structure.
*/
static let __default: RDSModel.DBParameterGroupNameMessage = {
let defaultInstance = RDSModel.DBParameterGroupNameMessage(
dBParameterGroupName: nil)
return defaultInstance
}()
}
public extension DBParameterGroupNameMessageForModifyDBParameterGroup {
/**
Default instance of the DBParameterGroupNameMessageForModifyDBParameterGroup structure.
*/
static let __default: RDSModel.DBParameterGroupNameMessageForModifyDBParameterGroup = {
let defaultInstance = RDSModel.DBParameterGroupNameMessageForModifyDBParameterGroup(
modifyDBParameterGroupResult: DBParameterGroupNameMessage.__default)
return defaultInstance
}()
}
public extension DBParameterGroupNameMessageForResetDBParameterGroup {
/**
Default instance of the DBParameterGroupNameMessageForResetDBParameterGroup structure.
*/
static let __default: RDSModel.DBParameterGroupNameMessageForResetDBParameterGroup = {
let defaultInstance = RDSModel.DBParameterGroupNameMessageForResetDBParameterGroup(
resetDBParameterGroupResult: DBParameterGroupNameMessage.__default)
return defaultInstance
}()
}
public extension DBParameterGroupNotFoundFault {
/**
Default instance of the DBParameterGroupNotFoundFault structure.
*/
static let __default: RDSModel.DBParameterGroupNotFoundFault = {
let defaultInstance = RDSModel.DBParameterGroupNotFoundFault()
return defaultInstance
}()
}
public extension DBParameterGroupQuotaExceededFault {
/**
Default instance of the DBParameterGroupQuotaExceededFault structure.
*/
static let __default: RDSModel.DBParameterGroupQuotaExceededFault = {
let defaultInstance = RDSModel.DBParameterGroupQuotaExceededFault()
return defaultInstance
}()
}
public extension DBParameterGroupStatus {
/**
Default instance of the DBParameterGroupStatus structure.
*/
static let __default: RDSModel.DBParameterGroupStatus = {
let defaultInstance = RDSModel.DBParameterGroupStatus(
dBParameterGroupName: nil,
parameterApplyStatus: nil)
return defaultInstance
}()
}
public extension DBParameterGroupsMessage {
/**
Default instance of the DBParameterGroupsMessage structure.
*/
static let __default: RDSModel.DBParameterGroupsMessage = {
let defaultInstance = RDSModel.DBParameterGroupsMessage(
dBParameterGroups: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBParameterGroupsMessageForDescribeDBParameterGroups {
/**
Default instance of the DBParameterGroupsMessageForDescribeDBParameterGroups structure.
*/
static let __default: RDSModel.DBParameterGroupsMessageForDescribeDBParameterGroups = {
let defaultInstance = RDSModel.DBParameterGroupsMessageForDescribeDBParameterGroups(
describeDBParameterGroupsResult: DBParameterGroupsMessage.__default)
return defaultInstance
}()
}
public extension DBProxy {
/**
Default instance of the DBProxy structure.
*/
static let __default: RDSModel.DBProxy = {
let defaultInstance = RDSModel.DBProxy(
auth: nil,
createdDate: nil,
dBProxyArn: nil,
dBProxyName: nil,
debugLogging: nil,
endpoint: nil,
engineFamily: nil,
idleClientTimeout: nil,
requireTLS: nil,
roleArn: nil,
status: nil,
updatedDate: nil,
vpcSecurityGroupIds: nil,
vpcSubnetIds: nil)
return defaultInstance
}()
}
public extension DBProxyAlreadyExistsFault {
/**
Default instance of the DBProxyAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBProxyAlreadyExistsFault = {
let defaultInstance = RDSModel.DBProxyAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBProxyNotFoundFault {
/**
Default instance of the DBProxyNotFoundFault structure.
*/
static let __default: RDSModel.DBProxyNotFoundFault = {
let defaultInstance = RDSModel.DBProxyNotFoundFault()
return defaultInstance
}()
}
public extension DBProxyQuotaExceededFault {
/**
Default instance of the DBProxyQuotaExceededFault structure.
*/
static let __default: RDSModel.DBProxyQuotaExceededFault = {
let defaultInstance = RDSModel.DBProxyQuotaExceededFault()
return defaultInstance
}()
}
public extension DBProxyTarget {
/**
Default instance of the DBProxyTarget structure.
*/
static let __default: RDSModel.DBProxyTarget = {
let defaultInstance = RDSModel.DBProxyTarget(
endpoint: nil,
port: nil,
rdsResourceId: nil,
targetArn: nil,
targetHealth: nil,
trackedClusterId: nil,
type: nil)
return defaultInstance
}()
}
public extension DBProxyTargetAlreadyRegisteredFault {
/**
Default instance of the DBProxyTargetAlreadyRegisteredFault structure.
*/
static let __default: RDSModel.DBProxyTargetAlreadyRegisteredFault = {
let defaultInstance = RDSModel.DBProxyTargetAlreadyRegisteredFault()
return defaultInstance
}()
}
public extension DBProxyTargetGroup {
/**
Default instance of the DBProxyTargetGroup structure.
*/
static let __default: RDSModel.DBProxyTargetGroup = {
let defaultInstance = RDSModel.DBProxyTargetGroup(
connectionPoolConfig: nil,
createdDate: nil,
dBProxyName: nil,
isDefault: nil,
status: nil,
targetGroupArn: nil,
targetGroupName: nil,
updatedDate: nil)
return defaultInstance
}()
}
public extension DBProxyTargetGroupNotFoundFault {
/**
Default instance of the DBProxyTargetGroupNotFoundFault structure.
*/
static let __default: RDSModel.DBProxyTargetGroupNotFoundFault = {
let defaultInstance = RDSModel.DBProxyTargetGroupNotFoundFault()
return defaultInstance
}()
}
public extension DBProxyTargetNotFoundFault {
/**
Default instance of the DBProxyTargetNotFoundFault structure.
*/
static let __default: RDSModel.DBProxyTargetNotFoundFault = {
let defaultInstance = RDSModel.DBProxyTargetNotFoundFault()
return defaultInstance
}()
}
public extension DBSecurityGroup {
/**
Default instance of the DBSecurityGroup structure.
*/
static let __default: RDSModel.DBSecurityGroup = {
let defaultInstance = RDSModel.DBSecurityGroup(
dBSecurityGroupArn: nil,
dBSecurityGroupDescription: nil,
dBSecurityGroupName: nil,
eC2SecurityGroups: nil,
iPRanges: nil,
ownerId: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension DBSecurityGroupAlreadyExistsFault {
/**
Default instance of the DBSecurityGroupAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBSecurityGroupAlreadyExistsFault = {
let defaultInstance = RDSModel.DBSecurityGroupAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBSecurityGroupMembership {
/**
Default instance of the DBSecurityGroupMembership structure.
*/
static let __default: RDSModel.DBSecurityGroupMembership = {
let defaultInstance = RDSModel.DBSecurityGroupMembership(
dBSecurityGroupName: nil,
status: nil)
return defaultInstance
}()
}
public extension DBSecurityGroupMessage {
/**
Default instance of the DBSecurityGroupMessage structure.
*/
static let __default: RDSModel.DBSecurityGroupMessage = {
let defaultInstance = RDSModel.DBSecurityGroupMessage(
dBSecurityGroups: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBSecurityGroupMessageForDescribeDBSecurityGroups {
/**
Default instance of the DBSecurityGroupMessageForDescribeDBSecurityGroups structure.
*/
static let __default: RDSModel.DBSecurityGroupMessageForDescribeDBSecurityGroups = {
let defaultInstance = RDSModel.DBSecurityGroupMessageForDescribeDBSecurityGroups(
describeDBSecurityGroupsResult: DBSecurityGroupMessage.__default)
return defaultInstance
}()
}
public extension DBSecurityGroupNotFoundFault {
/**
Default instance of the DBSecurityGroupNotFoundFault structure.
*/
static let __default: RDSModel.DBSecurityGroupNotFoundFault = {
let defaultInstance = RDSModel.DBSecurityGroupNotFoundFault()
return defaultInstance
}()
}
public extension DBSecurityGroupNotSupportedFault {
/**
Default instance of the DBSecurityGroupNotSupportedFault structure.
*/
static let __default: RDSModel.DBSecurityGroupNotSupportedFault = {
let defaultInstance = RDSModel.DBSecurityGroupNotSupportedFault()
return defaultInstance
}()
}
public extension DBSecurityGroupQuotaExceededFault {
/**
Default instance of the DBSecurityGroupQuotaExceededFault structure.
*/
static let __default: RDSModel.DBSecurityGroupQuotaExceededFault = {
let defaultInstance = RDSModel.DBSecurityGroupQuotaExceededFault()
return defaultInstance
}()
}
public extension DBSnapshot {
/**
Default instance of the DBSnapshot structure.
*/
static let __default: RDSModel.DBSnapshot = {
let defaultInstance = RDSModel.DBSnapshot(
allocatedStorage: nil,
availabilityZone: nil,
dBInstanceIdentifier: nil,
dBSnapshotArn: nil,
dBSnapshotIdentifier: nil,
dbiResourceId: nil,
encrypted: nil,
engine: nil,
engineVersion: nil,
iAMDatabaseAuthenticationEnabled: nil,
instanceCreateTime: nil,
iops: nil,
kmsKeyId: nil,
licenseModel: nil,
masterUsername: nil,
optionGroupName: nil,
percentProgress: nil,
port: nil,
processorFeatures: nil,
snapshotCreateTime: nil,
snapshotType: nil,
sourceDBSnapshotIdentifier: nil,
sourceRegion: nil,
status: nil,
storageType: nil,
tagList: nil,
tdeCredentialArn: nil,
timezone: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension DBSnapshotAlreadyExistsFault {
/**
Default instance of the DBSnapshotAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBSnapshotAlreadyExistsFault = {
let defaultInstance = RDSModel.DBSnapshotAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBSnapshotAttribute {
/**
Default instance of the DBSnapshotAttribute structure.
*/
static let __default: RDSModel.DBSnapshotAttribute = {
let defaultInstance = RDSModel.DBSnapshotAttribute(
attributeName: nil,
attributeValues: nil)
return defaultInstance
}()
}
public extension DBSnapshotAttributesResult {
/**
Default instance of the DBSnapshotAttributesResult structure.
*/
static let __default: RDSModel.DBSnapshotAttributesResult = {
let defaultInstance = RDSModel.DBSnapshotAttributesResult(
dBSnapshotAttributes: nil,
dBSnapshotIdentifier: nil)
return defaultInstance
}()
}
public extension DBSnapshotMessage {
/**
Default instance of the DBSnapshotMessage structure.
*/
static let __default: RDSModel.DBSnapshotMessage = {
let defaultInstance = RDSModel.DBSnapshotMessage(
dBSnapshots: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBSnapshotMessageForDescribeDBSnapshots {
/**
Default instance of the DBSnapshotMessageForDescribeDBSnapshots structure.
*/
static let __default: RDSModel.DBSnapshotMessageForDescribeDBSnapshots = {
let defaultInstance = RDSModel.DBSnapshotMessageForDescribeDBSnapshots(
describeDBSnapshotsResult: DBSnapshotMessage.__default)
return defaultInstance
}()
}
public extension DBSnapshotNotFoundFault {
/**
Default instance of the DBSnapshotNotFoundFault structure.
*/
static let __default: RDSModel.DBSnapshotNotFoundFault = {
let defaultInstance = RDSModel.DBSnapshotNotFoundFault()
return defaultInstance
}()
}
public extension DBSubnetGroup {
/**
Default instance of the DBSubnetGroup structure.
*/
static let __default: RDSModel.DBSubnetGroup = {
let defaultInstance = RDSModel.DBSubnetGroup(
dBSubnetGroupArn: nil,
dBSubnetGroupDescription: nil,
dBSubnetGroupName: nil,
subnetGroupStatus: nil,
subnets: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension DBSubnetGroupAlreadyExistsFault {
/**
Default instance of the DBSubnetGroupAlreadyExistsFault structure.
*/
static let __default: RDSModel.DBSubnetGroupAlreadyExistsFault = {
let defaultInstance = RDSModel.DBSubnetGroupAlreadyExistsFault()
return defaultInstance
}()
}
public extension DBSubnetGroupDoesNotCoverEnoughAZs {
/**
Default instance of the DBSubnetGroupDoesNotCoverEnoughAZs structure.
*/
static let __default: RDSModel.DBSubnetGroupDoesNotCoverEnoughAZs = {
let defaultInstance = RDSModel.DBSubnetGroupDoesNotCoverEnoughAZs()
return defaultInstance
}()
}
public extension DBSubnetGroupMessage {
/**
Default instance of the DBSubnetGroupMessage structure.
*/
static let __default: RDSModel.DBSubnetGroupMessage = {
let defaultInstance = RDSModel.DBSubnetGroupMessage(
dBSubnetGroups: nil,
marker: nil)
return defaultInstance
}()
}
public extension DBSubnetGroupMessageForDescribeDBSubnetGroups {
/**
Default instance of the DBSubnetGroupMessageForDescribeDBSubnetGroups structure.
*/
static let __default: RDSModel.DBSubnetGroupMessageForDescribeDBSubnetGroups = {
let defaultInstance = RDSModel.DBSubnetGroupMessageForDescribeDBSubnetGroups(
describeDBSubnetGroupsResult: DBSubnetGroupMessage.__default)
return defaultInstance
}()
}
public extension DBSubnetGroupNotAllowedFault {
/**
Default instance of the DBSubnetGroupNotAllowedFault structure.
*/
static let __default: RDSModel.DBSubnetGroupNotAllowedFault = {
let defaultInstance = RDSModel.DBSubnetGroupNotAllowedFault()
return defaultInstance
}()
}
public extension DBSubnetGroupNotFoundFault {
/**
Default instance of the DBSubnetGroupNotFoundFault structure.
*/
static let __default: RDSModel.DBSubnetGroupNotFoundFault = {
let defaultInstance = RDSModel.DBSubnetGroupNotFoundFault()
return defaultInstance
}()
}
public extension DBSubnetGroupQuotaExceededFault {
/**
Default instance of the DBSubnetGroupQuotaExceededFault structure.
*/
static let __default: RDSModel.DBSubnetGroupQuotaExceededFault = {
let defaultInstance = RDSModel.DBSubnetGroupQuotaExceededFault()
return defaultInstance
}()
}
public extension DBSubnetQuotaExceededFault {
/**
Default instance of the DBSubnetQuotaExceededFault structure.
*/
static let __default: RDSModel.DBSubnetQuotaExceededFault = {
let defaultInstance = RDSModel.DBSubnetQuotaExceededFault()
return defaultInstance
}()
}
public extension DBUpgradeDependencyFailureFault {
/**
Default instance of the DBUpgradeDependencyFailureFault structure.
*/
static let __default: RDSModel.DBUpgradeDependencyFailureFault = {
let defaultInstance = RDSModel.DBUpgradeDependencyFailureFault()
return defaultInstance
}()
}
public extension DeleteCustomAvailabilityZoneMessage {
/**
Default instance of the DeleteCustomAvailabilityZoneMessage structure.
*/
static let __default: RDSModel.DeleteCustomAvailabilityZoneMessage = {
let defaultInstance = RDSModel.DeleteCustomAvailabilityZoneMessage(
customAvailabilityZoneId: "value")
return defaultInstance
}()
}
public extension DeleteCustomAvailabilityZoneResult {
/**
Default instance of the DeleteCustomAvailabilityZoneResult structure.
*/
static let __default: RDSModel.DeleteCustomAvailabilityZoneResult = {
let defaultInstance = RDSModel.DeleteCustomAvailabilityZoneResult(
customAvailabilityZone: nil)
return defaultInstance
}()
}
public extension DeleteCustomAvailabilityZoneResultForDeleteCustomAvailabilityZone {
/**
Default instance of the DeleteCustomAvailabilityZoneResultForDeleteCustomAvailabilityZone structure.
*/
static let __default: RDSModel.DeleteCustomAvailabilityZoneResultForDeleteCustomAvailabilityZone = {
let defaultInstance = RDSModel.DeleteCustomAvailabilityZoneResultForDeleteCustomAvailabilityZone(
deleteCustomAvailabilityZoneResult: DeleteCustomAvailabilityZoneResult.__default)
return defaultInstance
}()
}
public extension DeleteDBClusterEndpointMessage {
/**
Default instance of the DeleteDBClusterEndpointMessage structure.
*/
static let __default: RDSModel.DeleteDBClusterEndpointMessage = {
let defaultInstance = RDSModel.DeleteDBClusterEndpointMessage(
dBClusterEndpointIdentifier: "value")
return defaultInstance
}()
}
public extension DeleteDBClusterMessage {
/**
Default instance of the DeleteDBClusterMessage structure.
*/
static let __default: RDSModel.DeleteDBClusterMessage = {
let defaultInstance = RDSModel.DeleteDBClusterMessage(
dBClusterIdentifier: "value",
finalDBSnapshotIdentifier: nil,
skipFinalSnapshot: nil)
return defaultInstance
}()
}
public extension DeleteDBClusterParameterGroupMessage {
/**
Default instance of the DeleteDBClusterParameterGroupMessage structure.
*/
static let __default: RDSModel.DeleteDBClusterParameterGroupMessage = {
let defaultInstance = RDSModel.DeleteDBClusterParameterGroupMessage(
dBClusterParameterGroupName: "value")
return defaultInstance
}()
}
public extension DeleteDBClusterResult {
/**
Default instance of the DeleteDBClusterResult structure.
*/
static let __default: RDSModel.DeleteDBClusterResult = {
let defaultInstance = RDSModel.DeleteDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension DeleteDBClusterResultForDeleteDBCluster {
/**
Default instance of the DeleteDBClusterResultForDeleteDBCluster structure.
*/
static let __default: RDSModel.DeleteDBClusterResultForDeleteDBCluster = {
let defaultInstance = RDSModel.DeleteDBClusterResultForDeleteDBCluster(
deleteDBClusterResult: DeleteDBClusterResult.__default)
return defaultInstance
}()
}
public extension DeleteDBClusterSnapshotMessage {
/**
Default instance of the DeleteDBClusterSnapshotMessage structure.
*/
static let __default: RDSModel.DeleteDBClusterSnapshotMessage = {
let defaultInstance = RDSModel.DeleteDBClusterSnapshotMessage(
dBClusterSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension DeleteDBClusterSnapshotResult {
/**
Default instance of the DeleteDBClusterSnapshotResult structure.
*/
static let __default: RDSModel.DeleteDBClusterSnapshotResult = {
let defaultInstance = RDSModel.DeleteDBClusterSnapshotResult(
dBClusterSnapshot: nil)
return defaultInstance
}()
}
public extension DeleteDBClusterSnapshotResultForDeleteDBClusterSnapshot {
/**
Default instance of the DeleteDBClusterSnapshotResultForDeleteDBClusterSnapshot structure.
*/
static let __default: RDSModel.DeleteDBClusterSnapshotResultForDeleteDBClusterSnapshot = {
let defaultInstance = RDSModel.DeleteDBClusterSnapshotResultForDeleteDBClusterSnapshot(
deleteDBClusterSnapshotResult: DeleteDBClusterSnapshotResult.__default)
return defaultInstance
}()
}
public extension DeleteDBInstanceAutomatedBackupMessage {
/**
Default instance of the DeleteDBInstanceAutomatedBackupMessage structure.
*/
static let __default: RDSModel.DeleteDBInstanceAutomatedBackupMessage = {
let defaultInstance = RDSModel.DeleteDBInstanceAutomatedBackupMessage(
dbiResourceId: "value")
return defaultInstance
}()
}
public extension DeleteDBInstanceAutomatedBackupResult {
/**
Default instance of the DeleteDBInstanceAutomatedBackupResult structure.
*/
static let __default: RDSModel.DeleteDBInstanceAutomatedBackupResult = {
let defaultInstance = RDSModel.DeleteDBInstanceAutomatedBackupResult(
dBInstanceAutomatedBackup: nil)
return defaultInstance
}()
}
public extension DeleteDBInstanceAutomatedBackupResultForDeleteDBInstanceAutomatedBackup {
/**
Default instance of the DeleteDBInstanceAutomatedBackupResultForDeleteDBInstanceAutomatedBackup structure.
*/
static let __default: RDSModel.DeleteDBInstanceAutomatedBackupResultForDeleteDBInstanceAutomatedBackup = {
let defaultInstance = RDSModel.DeleteDBInstanceAutomatedBackupResultForDeleteDBInstanceAutomatedBackup(
deleteDBInstanceAutomatedBackupResult: DeleteDBInstanceAutomatedBackupResult.__default)
return defaultInstance
}()
}
public extension DeleteDBInstanceMessage {
/**
Default instance of the DeleteDBInstanceMessage structure.
*/
static let __default: RDSModel.DeleteDBInstanceMessage = {
let defaultInstance = RDSModel.DeleteDBInstanceMessage(
dBInstanceIdentifier: "value",
deleteAutomatedBackups: nil,
finalDBSnapshotIdentifier: nil,
skipFinalSnapshot: nil)
return defaultInstance
}()
}
public extension DeleteDBInstanceResult {
/**
Default instance of the DeleteDBInstanceResult structure.
*/
static let __default: RDSModel.DeleteDBInstanceResult = {
let defaultInstance = RDSModel.DeleteDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension DeleteDBInstanceResultForDeleteDBInstance {
/**
Default instance of the DeleteDBInstanceResultForDeleteDBInstance structure.
*/
static let __default: RDSModel.DeleteDBInstanceResultForDeleteDBInstance = {
let defaultInstance = RDSModel.DeleteDBInstanceResultForDeleteDBInstance(
deleteDBInstanceResult: DeleteDBInstanceResult.__default)
return defaultInstance
}()
}
public extension DeleteDBParameterGroupMessage {
/**
Default instance of the DeleteDBParameterGroupMessage structure.
*/
static let __default: RDSModel.DeleteDBParameterGroupMessage = {
let defaultInstance = RDSModel.DeleteDBParameterGroupMessage(
dBParameterGroupName: "value")
return defaultInstance
}()
}
public extension DeleteDBProxyRequest {
/**
Default instance of the DeleteDBProxyRequest structure.
*/
static let __default: RDSModel.DeleteDBProxyRequest = {
let defaultInstance = RDSModel.DeleteDBProxyRequest(
dBProxyName: "value")
return defaultInstance
}()
}
public extension DeleteDBProxyResponse {
/**
Default instance of the DeleteDBProxyResponse structure.
*/
static let __default: RDSModel.DeleteDBProxyResponse = {
let defaultInstance = RDSModel.DeleteDBProxyResponse(
dBProxy: nil)
return defaultInstance
}()
}
public extension DeleteDBProxyResponseForDeleteDBProxy {
/**
Default instance of the DeleteDBProxyResponseForDeleteDBProxy structure.
*/
static let __default: RDSModel.DeleteDBProxyResponseForDeleteDBProxy = {
let defaultInstance = RDSModel.DeleteDBProxyResponseForDeleteDBProxy(
deleteDBProxyResult: DeleteDBProxyResponse.__default)
return defaultInstance
}()
}
public extension DeleteDBSecurityGroupMessage {
/**
Default instance of the DeleteDBSecurityGroupMessage structure.
*/
static let __default: RDSModel.DeleteDBSecurityGroupMessage = {
let defaultInstance = RDSModel.DeleteDBSecurityGroupMessage(
dBSecurityGroupName: "value")
return defaultInstance
}()
}
public extension DeleteDBSnapshotMessage {
/**
Default instance of the DeleteDBSnapshotMessage structure.
*/
static let __default: RDSModel.DeleteDBSnapshotMessage = {
let defaultInstance = RDSModel.DeleteDBSnapshotMessage(
dBSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension DeleteDBSnapshotResult {
/**
Default instance of the DeleteDBSnapshotResult structure.
*/
static let __default: RDSModel.DeleteDBSnapshotResult = {
let defaultInstance = RDSModel.DeleteDBSnapshotResult(
dBSnapshot: nil)
return defaultInstance
}()
}
public extension DeleteDBSnapshotResultForDeleteDBSnapshot {
/**
Default instance of the DeleteDBSnapshotResultForDeleteDBSnapshot structure.
*/
static let __default: RDSModel.DeleteDBSnapshotResultForDeleteDBSnapshot = {
let defaultInstance = RDSModel.DeleteDBSnapshotResultForDeleteDBSnapshot(
deleteDBSnapshotResult: DeleteDBSnapshotResult.__default)
return defaultInstance
}()
}
public extension DeleteDBSubnetGroupMessage {
/**
Default instance of the DeleteDBSubnetGroupMessage structure.
*/
static let __default: RDSModel.DeleteDBSubnetGroupMessage = {
let defaultInstance = RDSModel.DeleteDBSubnetGroupMessage(
dBSubnetGroupName: "value")
return defaultInstance
}()
}
public extension DeleteEventSubscriptionMessage {
/**
Default instance of the DeleteEventSubscriptionMessage structure.
*/
static let __default: RDSModel.DeleteEventSubscriptionMessage = {
let defaultInstance = RDSModel.DeleteEventSubscriptionMessage(
subscriptionName: "value")
return defaultInstance
}()
}
public extension DeleteEventSubscriptionResult {
/**
Default instance of the DeleteEventSubscriptionResult structure.
*/
static let __default: RDSModel.DeleteEventSubscriptionResult = {
let defaultInstance = RDSModel.DeleteEventSubscriptionResult(
eventSubscription: nil)
return defaultInstance
}()
}
public extension DeleteEventSubscriptionResultForDeleteEventSubscription {
/**
Default instance of the DeleteEventSubscriptionResultForDeleteEventSubscription structure.
*/
static let __default: RDSModel.DeleteEventSubscriptionResultForDeleteEventSubscription = {
let defaultInstance = RDSModel.DeleteEventSubscriptionResultForDeleteEventSubscription(
deleteEventSubscriptionResult: DeleteEventSubscriptionResult.__default)
return defaultInstance
}()
}
public extension DeleteGlobalClusterMessage {
/**
Default instance of the DeleteGlobalClusterMessage structure.
*/
static let __default: RDSModel.DeleteGlobalClusterMessage = {
let defaultInstance = RDSModel.DeleteGlobalClusterMessage(
globalClusterIdentifier: "value")
return defaultInstance
}()
}
public extension DeleteGlobalClusterResult {
/**
Default instance of the DeleteGlobalClusterResult structure.
*/
static let __default: RDSModel.DeleteGlobalClusterResult = {
let defaultInstance = RDSModel.DeleteGlobalClusterResult(
globalCluster: nil)
return defaultInstance
}()
}
public extension DeleteGlobalClusterResultForDeleteGlobalCluster {
/**
Default instance of the DeleteGlobalClusterResultForDeleteGlobalCluster structure.
*/
static let __default: RDSModel.DeleteGlobalClusterResultForDeleteGlobalCluster = {
let defaultInstance = RDSModel.DeleteGlobalClusterResultForDeleteGlobalCluster(
deleteGlobalClusterResult: DeleteGlobalClusterResult.__default)
return defaultInstance
}()
}
public extension DeleteInstallationMediaMessage {
/**
Default instance of the DeleteInstallationMediaMessage structure.
*/
static let __default: RDSModel.DeleteInstallationMediaMessage = {
let defaultInstance = RDSModel.DeleteInstallationMediaMessage(
installationMediaId: "value")
return defaultInstance
}()
}
public extension DeleteOptionGroupMessage {
/**
Default instance of the DeleteOptionGroupMessage structure.
*/
static let __default: RDSModel.DeleteOptionGroupMessage = {
let defaultInstance = RDSModel.DeleteOptionGroupMessage(
optionGroupName: "value")
return defaultInstance
}()
}
public extension DeregisterDBProxyTargetsRequest {
/**
Default instance of the DeregisterDBProxyTargetsRequest structure.
*/
static let __default: RDSModel.DeregisterDBProxyTargetsRequest = {
let defaultInstance = RDSModel.DeregisterDBProxyTargetsRequest(
dBClusterIdentifiers: nil,
dBInstanceIdentifiers: nil,
dBProxyName: "value",
targetGroupName: nil)
return defaultInstance
}()
}
public extension DeregisterDBProxyTargetsResponse {
/**
Default instance of the DeregisterDBProxyTargetsResponse structure.
*/
static let __default: RDSModel.DeregisterDBProxyTargetsResponse = {
let defaultInstance = RDSModel.DeregisterDBProxyTargetsResponse()
return defaultInstance
}()
}
public extension DeregisterDBProxyTargetsResponseForDeregisterDBProxyTargets {
/**
Default instance of the DeregisterDBProxyTargetsResponseForDeregisterDBProxyTargets structure.
*/
static let __default: RDSModel.DeregisterDBProxyTargetsResponseForDeregisterDBProxyTargets = {
let defaultInstance = RDSModel.DeregisterDBProxyTargetsResponseForDeregisterDBProxyTargets(
deregisterDBProxyTargetsResult: DeregisterDBProxyTargetsResponse.__default)
return defaultInstance
}()
}
public extension DescribeAccountAttributesMessage {
/**
Default instance of the DescribeAccountAttributesMessage structure.
*/
static let __default: RDSModel.DescribeAccountAttributesMessage = {
let defaultInstance = RDSModel.DescribeAccountAttributesMessage()
return defaultInstance
}()
}
public extension DescribeCertificatesMessage {
/**
Default instance of the DescribeCertificatesMessage structure.
*/
static let __default: RDSModel.DescribeCertificatesMessage = {
let defaultInstance = RDSModel.DescribeCertificatesMessage(
certificateIdentifier: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeCustomAvailabilityZonesMessage {
/**
Default instance of the DescribeCustomAvailabilityZonesMessage structure.
*/
static let __default: RDSModel.DescribeCustomAvailabilityZonesMessage = {
let defaultInstance = RDSModel.DescribeCustomAvailabilityZonesMessage(
customAvailabilityZoneId: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterBacktracksMessage {
/**
Default instance of the DescribeDBClusterBacktracksMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterBacktracksMessage = {
let defaultInstance = RDSModel.DescribeDBClusterBacktracksMessage(
backtrackIdentifier: nil,
dBClusterIdentifier: "value",
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterEndpointsMessage {
/**
Default instance of the DescribeDBClusterEndpointsMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterEndpointsMessage = {
let defaultInstance = RDSModel.DescribeDBClusterEndpointsMessage(
dBClusterEndpointIdentifier: nil,
dBClusterIdentifier: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterParameterGroupsMessage {
/**
Default instance of the DescribeDBClusterParameterGroupsMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterParameterGroupsMessage = {
let defaultInstance = RDSModel.DescribeDBClusterParameterGroupsMessage(
dBClusterParameterGroupName: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterParametersMessage {
/**
Default instance of the DescribeDBClusterParametersMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterParametersMessage = {
let defaultInstance = RDSModel.DescribeDBClusterParametersMessage(
dBClusterParameterGroupName: "value",
filters: nil,
marker: nil,
maxRecords: nil,
source: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterSnapshotAttributesMessage {
/**
Default instance of the DescribeDBClusterSnapshotAttributesMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterSnapshotAttributesMessage = {
let defaultInstance = RDSModel.DescribeDBClusterSnapshotAttributesMessage(
dBClusterSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension DescribeDBClusterSnapshotAttributesResult {
/**
Default instance of the DescribeDBClusterSnapshotAttributesResult structure.
*/
static let __default: RDSModel.DescribeDBClusterSnapshotAttributesResult = {
let defaultInstance = RDSModel.DescribeDBClusterSnapshotAttributesResult(
dBClusterSnapshotAttributesResult: nil)
return defaultInstance
}()
}
public extension DescribeDBClusterSnapshotAttributesResultForDescribeDBClusterSnapshotAttributes {
/**
Default instance of the DescribeDBClusterSnapshotAttributesResultForDescribeDBClusterSnapshotAttributes structure.
*/
static let __default: RDSModel.DescribeDBClusterSnapshotAttributesResultForDescribeDBClusterSnapshotAttributes = {
let defaultInstance = RDSModel.DescribeDBClusterSnapshotAttributesResultForDescribeDBClusterSnapshotAttributes(
describeDBClusterSnapshotAttributesResult: DescribeDBClusterSnapshotAttributesResult.__default)
return defaultInstance
}()
}
public extension DescribeDBClusterSnapshotsMessage {
/**
Default instance of the DescribeDBClusterSnapshotsMessage structure.
*/
static let __default: RDSModel.DescribeDBClusterSnapshotsMessage = {
let defaultInstance = RDSModel.DescribeDBClusterSnapshotsMessage(
dBClusterIdentifier: nil,
dBClusterSnapshotIdentifier: nil,
filters: nil,
includePublic: nil,
includeShared: nil,
marker: nil,
maxRecords: nil,
snapshotType: nil)
return defaultInstance
}()
}
public extension DescribeDBClustersMessage {
/**
Default instance of the DescribeDBClustersMessage structure.
*/
static let __default: RDSModel.DescribeDBClustersMessage = {
let defaultInstance = RDSModel.DescribeDBClustersMessage(
dBClusterIdentifier: nil,
filters: nil,
includeShared: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBEngineVersionsMessage {
/**
Default instance of the DescribeDBEngineVersionsMessage structure.
*/
static let __default: RDSModel.DescribeDBEngineVersionsMessage = {
let defaultInstance = RDSModel.DescribeDBEngineVersionsMessage(
dBParameterGroupFamily: nil,
defaultOnly: nil,
engine: nil,
engineVersion: nil,
filters: nil,
includeAll: nil,
listSupportedCharacterSets: nil,
listSupportedTimezones: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBInstanceAutomatedBackupsMessage {
/**
Default instance of the DescribeDBInstanceAutomatedBackupsMessage structure.
*/
static let __default: RDSModel.DescribeDBInstanceAutomatedBackupsMessage = {
let defaultInstance = RDSModel.DescribeDBInstanceAutomatedBackupsMessage(
dBInstanceIdentifier: nil,
dbiResourceId: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBInstancesMessage {
/**
Default instance of the DescribeDBInstancesMessage structure.
*/
static let __default: RDSModel.DescribeDBInstancesMessage = {
let defaultInstance = RDSModel.DescribeDBInstancesMessage(
dBInstanceIdentifier: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBLogFilesDetails {
/**
Default instance of the DescribeDBLogFilesDetails structure.
*/
static let __default: RDSModel.DescribeDBLogFilesDetails = {
let defaultInstance = RDSModel.DescribeDBLogFilesDetails(
lastWritten: nil,
logFileName: nil,
size: nil)
return defaultInstance
}()
}
public extension DescribeDBLogFilesMessage {
/**
Default instance of the DescribeDBLogFilesMessage structure.
*/
static let __default: RDSModel.DescribeDBLogFilesMessage = {
let defaultInstance = RDSModel.DescribeDBLogFilesMessage(
dBInstanceIdentifier: "value",
fileLastWritten: nil,
fileSize: nil,
filenameContains: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBLogFilesResponse {
/**
Default instance of the DescribeDBLogFilesResponse structure.
*/
static let __default: RDSModel.DescribeDBLogFilesResponse = {
let defaultInstance = RDSModel.DescribeDBLogFilesResponse(
describeDBLogFiles: nil,
marker: nil)
return defaultInstance
}()
}
public extension DescribeDBLogFilesResponseForDescribeDBLogFiles {
/**
Default instance of the DescribeDBLogFilesResponseForDescribeDBLogFiles structure.
*/
static let __default: RDSModel.DescribeDBLogFilesResponseForDescribeDBLogFiles = {
let defaultInstance = RDSModel.DescribeDBLogFilesResponseForDescribeDBLogFiles(
describeDBLogFilesResult: DescribeDBLogFilesResponse.__default)
return defaultInstance
}()
}
public extension DescribeDBParameterGroupsMessage {
/**
Default instance of the DescribeDBParameterGroupsMessage structure.
*/
static let __default: RDSModel.DescribeDBParameterGroupsMessage = {
let defaultInstance = RDSModel.DescribeDBParameterGroupsMessage(
dBParameterGroupName: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBParametersMessage {
/**
Default instance of the DescribeDBParametersMessage structure.
*/
static let __default: RDSModel.DescribeDBParametersMessage = {
let defaultInstance = RDSModel.DescribeDBParametersMessage(
dBParameterGroupName: "value",
filters: nil,
marker: nil,
maxRecords: nil,
source: nil)
return defaultInstance
}()
}
public extension DescribeDBProxiesRequest {
/**
Default instance of the DescribeDBProxiesRequest structure.
*/
static let __default: RDSModel.DescribeDBProxiesRequest = {
let defaultInstance = RDSModel.DescribeDBProxiesRequest(
dBProxyName: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBProxiesResponse {
/**
Default instance of the DescribeDBProxiesResponse structure.
*/
static let __default: RDSModel.DescribeDBProxiesResponse = {
let defaultInstance = RDSModel.DescribeDBProxiesResponse(
dBProxies: nil,
marker: nil)
return defaultInstance
}()
}
public extension DescribeDBProxiesResponseForDescribeDBProxies {
/**
Default instance of the DescribeDBProxiesResponseForDescribeDBProxies structure.
*/
static let __default: RDSModel.DescribeDBProxiesResponseForDescribeDBProxies = {
let defaultInstance = RDSModel.DescribeDBProxiesResponseForDescribeDBProxies(
describeDBProxiesResult: DescribeDBProxiesResponse.__default)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetGroupsRequest {
/**
Default instance of the DescribeDBProxyTargetGroupsRequest structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetGroupsRequest = {
let defaultInstance = RDSModel.DescribeDBProxyTargetGroupsRequest(
dBProxyName: "value",
filters: nil,
marker: nil,
maxRecords: nil,
targetGroupName: nil)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetGroupsResponse {
/**
Default instance of the DescribeDBProxyTargetGroupsResponse structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetGroupsResponse = {
let defaultInstance = RDSModel.DescribeDBProxyTargetGroupsResponse(
marker: nil,
targetGroups: nil)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetGroupsResponseForDescribeDBProxyTargetGroups {
/**
Default instance of the DescribeDBProxyTargetGroupsResponseForDescribeDBProxyTargetGroups structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetGroupsResponseForDescribeDBProxyTargetGroups = {
let defaultInstance = RDSModel.DescribeDBProxyTargetGroupsResponseForDescribeDBProxyTargetGroups(
describeDBProxyTargetGroupsResult: DescribeDBProxyTargetGroupsResponse.__default)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetsRequest {
/**
Default instance of the DescribeDBProxyTargetsRequest structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetsRequest = {
let defaultInstance = RDSModel.DescribeDBProxyTargetsRequest(
dBProxyName: "value",
filters: nil,
marker: nil,
maxRecords: nil,
targetGroupName: nil)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetsResponse {
/**
Default instance of the DescribeDBProxyTargetsResponse structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetsResponse = {
let defaultInstance = RDSModel.DescribeDBProxyTargetsResponse(
marker: nil,
targets: nil)
return defaultInstance
}()
}
public extension DescribeDBProxyTargetsResponseForDescribeDBProxyTargets {
/**
Default instance of the DescribeDBProxyTargetsResponseForDescribeDBProxyTargets structure.
*/
static let __default: RDSModel.DescribeDBProxyTargetsResponseForDescribeDBProxyTargets = {
let defaultInstance = RDSModel.DescribeDBProxyTargetsResponseForDescribeDBProxyTargets(
describeDBProxyTargetsResult: DescribeDBProxyTargetsResponse.__default)
return defaultInstance
}()
}
public extension DescribeDBSecurityGroupsMessage {
/**
Default instance of the DescribeDBSecurityGroupsMessage structure.
*/
static let __default: RDSModel.DescribeDBSecurityGroupsMessage = {
let defaultInstance = RDSModel.DescribeDBSecurityGroupsMessage(
dBSecurityGroupName: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeDBSnapshotAttributesMessage {
/**
Default instance of the DescribeDBSnapshotAttributesMessage structure.
*/
static let __default: RDSModel.DescribeDBSnapshotAttributesMessage = {
let defaultInstance = RDSModel.DescribeDBSnapshotAttributesMessage(
dBSnapshotIdentifier: "value")
return defaultInstance
}()
}
public extension DescribeDBSnapshotAttributesResult {
/**
Default instance of the DescribeDBSnapshotAttributesResult structure.
*/
static let __default: RDSModel.DescribeDBSnapshotAttributesResult = {
let defaultInstance = RDSModel.DescribeDBSnapshotAttributesResult(
dBSnapshotAttributesResult: nil)
return defaultInstance
}()
}
public extension DescribeDBSnapshotAttributesResultForDescribeDBSnapshotAttributes {
/**
Default instance of the DescribeDBSnapshotAttributesResultForDescribeDBSnapshotAttributes structure.
*/
static let __default: RDSModel.DescribeDBSnapshotAttributesResultForDescribeDBSnapshotAttributes = {
let defaultInstance = RDSModel.DescribeDBSnapshotAttributesResultForDescribeDBSnapshotAttributes(
describeDBSnapshotAttributesResult: DescribeDBSnapshotAttributesResult.__default)
return defaultInstance
}()
}
public extension DescribeDBSnapshotsMessage {
/**
Default instance of the DescribeDBSnapshotsMessage structure.
*/
static let __default: RDSModel.DescribeDBSnapshotsMessage = {
let defaultInstance = RDSModel.DescribeDBSnapshotsMessage(
dBInstanceIdentifier: nil,
dBSnapshotIdentifier: nil,
dbiResourceId: nil,
filters: nil,
includePublic: nil,
includeShared: nil,
marker: nil,
maxRecords: nil,
snapshotType: nil)
return defaultInstance
}()
}
public extension DescribeDBSubnetGroupsMessage {
/**
Default instance of the DescribeDBSubnetGroupsMessage structure.
*/
static let __default: RDSModel.DescribeDBSubnetGroupsMessage = {
let defaultInstance = RDSModel.DescribeDBSubnetGroupsMessage(
dBSubnetGroupName: nil,
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeEngineDefaultClusterParametersMessage {
/**
Default instance of the DescribeEngineDefaultClusterParametersMessage structure.
*/
static let __default: RDSModel.DescribeEngineDefaultClusterParametersMessage = {
let defaultInstance = RDSModel.DescribeEngineDefaultClusterParametersMessage(
dBParameterGroupFamily: "value",
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeEngineDefaultClusterParametersResult {
/**
Default instance of the DescribeEngineDefaultClusterParametersResult structure.
*/
static let __default: RDSModel.DescribeEngineDefaultClusterParametersResult = {
let defaultInstance = RDSModel.DescribeEngineDefaultClusterParametersResult(
engineDefaults: nil)
return defaultInstance
}()
}
public extension DescribeEngineDefaultClusterParametersResultForDescribeEngineDefaultClusterParameters {
/**
Default instance of the DescribeEngineDefaultClusterParametersResultForDescribeEngineDefaultClusterParameters structure.
*/
static let __default: RDSModel.DescribeEngineDefaultClusterParametersResultForDescribeEngineDefaultClusterParameters = {
let defaultInstance = RDSModel.DescribeEngineDefaultClusterParametersResultForDescribeEngineDefaultClusterParameters(
describeEngineDefaultClusterParametersResult: DescribeEngineDefaultClusterParametersResult.__default)
return defaultInstance
}()
}
public extension DescribeEngineDefaultParametersMessage {
/**
Default instance of the DescribeEngineDefaultParametersMessage structure.
*/
static let __default: RDSModel.DescribeEngineDefaultParametersMessage = {
let defaultInstance = RDSModel.DescribeEngineDefaultParametersMessage(
dBParameterGroupFamily: "value",
filters: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeEngineDefaultParametersResult {
/**
Default instance of the DescribeEngineDefaultParametersResult structure.
*/
static let __default: RDSModel.DescribeEngineDefaultParametersResult = {
let defaultInstance = RDSModel.DescribeEngineDefaultParametersResult(
engineDefaults: nil)
return defaultInstance
}()
}
public extension DescribeEngineDefaultParametersResultForDescribeEngineDefaultParameters {
/**
Default instance of the DescribeEngineDefaultParametersResultForDescribeEngineDefaultParameters structure.
*/
static let __default: RDSModel.DescribeEngineDefaultParametersResultForDescribeEngineDefaultParameters = {
let defaultInstance = RDSModel.DescribeEngineDefaultParametersResultForDescribeEngineDefaultParameters(
describeEngineDefaultParametersResult: DescribeEngineDefaultParametersResult.__default)
return defaultInstance
}()
}
public extension DescribeEventCategoriesMessage {
/**
Default instance of the DescribeEventCategoriesMessage structure.
*/
static let __default: RDSModel.DescribeEventCategoriesMessage = {
let defaultInstance = RDSModel.DescribeEventCategoriesMessage(
filters: nil,
sourceType: nil)
return defaultInstance
}()
}
public extension DescribeEventSubscriptionsMessage {
/**
Default instance of the DescribeEventSubscriptionsMessage structure.
*/
static let __default: RDSModel.DescribeEventSubscriptionsMessage = {
let defaultInstance = RDSModel.DescribeEventSubscriptionsMessage(
filters: nil,
marker: nil,
maxRecords: nil,
subscriptionName: nil)
return defaultInstance
}()
}
public extension DescribeEventsMessage {
/**
Default instance of the DescribeEventsMessage structure.
*/
static let __default: RDSModel.DescribeEventsMessage = {
let defaultInstance = RDSModel.DescribeEventsMessage(
duration: nil,
endTime: nil,
eventCategories: nil,
filters: nil,
marker: nil,
maxRecords: nil,
sourceIdentifier: nil,
sourceType: nil,
startTime: nil)
return defaultInstance
}()
}
public extension DescribeExportTasksMessage {
/**
Default instance of the DescribeExportTasksMessage structure.
*/
static let __default: RDSModel.DescribeExportTasksMessage = {
let defaultInstance = RDSModel.DescribeExportTasksMessage(
exportTaskIdentifier: nil,
filters: nil,
marker: nil,
maxRecords: nil,
sourceArn: nil)
return defaultInstance
}()
}
public extension DescribeGlobalClustersMessage {
/**
Default instance of the DescribeGlobalClustersMessage structure.
*/
static let __default: RDSModel.DescribeGlobalClustersMessage = {
let defaultInstance = RDSModel.DescribeGlobalClustersMessage(
filters: nil,
globalClusterIdentifier: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeInstallationMediaMessage {
/**
Default instance of the DescribeInstallationMediaMessage structure.
*/
static let __default: RDSModel.DescribeInstallationMediaMessage = {
let defaultInstance = RDSModel.DescribeInstallationMediaMessage(
filters: nil,
installationMediaId: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeOptionGroupOptionsMessage {
/**
Default instance of the DescribeOptionGroupOptionsMessage structure.
*/
static let __default: RDSModel.DescribeOptionGroupOptionsMessage = {
let defaultInstance = RDSModel.DescribeOptionGroupOptionsMessage(
engineName: "value",
filters: nil,
majorEngineVersion: nil,
marker: nil,
maxRecords: nil)
return defaultInstance
}()
}
public extension DescribeOptionGroupsMessage {
/**
Default instance of the DescribeOptionGroupsMessage structure.
*/
static let __default: RDSModel.DescribeOptionGroupsMessage = {
let defaultInstance = RDSModel.DescribeOptionGroupsMessage(
engineName: nil,
filters: nil,
majorEngineVersion: nil,
marker: nil,
maxRecords: nil,
optionGroupName: nil)
return defaultInstance
}()
}
public extension DescribeOrderableDBInstanceOptionsMessage {
/**
Default instance of the DescribeOrderableDBInstanceOptionsMessage structure.
*/
static let __default: RDSModel.DescribeOrderableDBInstanceOptionsMessage = {
let defaultInstance = RDSModel.DescribeOrderableDBInstanceOptionsMessage(
availabilityZoneGroup: nil,
dBInstanceClass: nil,
engine: "value",
engineVersion: nil,
filters: nil,
licenseModel: nil,
marker: nil,
maxRecords: nil,
vpc: nil)
return defaultInstance
}()
}
public extension DescribePendingMaintenanceActionsMessage {
/**
Default instance of the DescribePendingMaintenanceActionsMessage structure.
*/
static let __default: RDSModel.DescribePendingMaintenanceActionsMessage = {
let defaultInstance = RDSModel.DescribePendingMaintenanceActionsMessage(
filters: nil,
marker: nil,
maxRecords: nil,
resourceIdentifier: nil)
return defaultInstance
}()
}
public extension DescribeReservedDBInstancesMessage {
/**
Default instance of the DescribeReservedDBInstancesMessage structure.
*/
static let __default: RDSModel.DescribeReservedDBInstancesMessage = {
let defaultInstance = RDSModel.DescribeReservedDBInstancesMessage(
dBInstanceClass: nil,
duration: nil,
filters: nil,
leaseId: nil,
marker: nil,
maxRecords: nil,
multiAZ: nil,
offeringType: nil,
productDescription: nil,
reservedDBInstanceId: nil,
reservedDBInstancesOfferingId: nil)
return defaultInstance
}()
}
public extension DescribeReservedDBInstancesOfferingsMessage {
/**
Default instance of the DescribeReservedDBInstancesOfferingsMessage structure.
*/
static let __default: RDSModel.DescribeReservedDBInstancesOfferingsMessage = {
let defaultInstance = RDSModel.DescribeReservedDBInstancesOfferingsMessage(
dBInstanceClass: nil,
duration: nil,
filters: nil,
marker: nil,
maxRecords: nil,
multiAZ: nil,
offeringType: nil,
productDescription: nil,
reservedDBInstancesOfferingId: nil)
return defaultInstance
}()
}
public extension DescribeSourceRegionsMessage {
/**
Default instance of the DescribeSourceRegionsMessage structure.
*/
static let __default: RDSModel.DescribeSourceRegionsMessage = {
let defaultInstance = RDSModel.DescribeSourceRegionsMessage(
filters: nil,
marker: nil,
maxRecords: nil,
regionName: nil)
return defaultInstance
}()
}
public extension DescribeValidDBInstanceModificationsMessage {
/**
Default instance of the DescribeValidDBInstanceModificationsMessage structure.
*/
static let __default: RDSModel.DescribeValidDBInstanceModificationsMessage = {
let defaultInstance = RDSModel.DescribeValidDBInstanceModificationsMessage(
dBInstanceIdentifier: "value")
return defaultInstance
}()
}
public extension DescribeValidDBInstanceModificationsResult {
/**
Default instance of the DescribeValidDBInstanceModificationsResult structure.
*/
static let __default: RDSModel.DescribeValidDBInstanceModificationsResult = {
let defaultInstance = RDSModel.DescribeValidDBInstanceModificationsResult(
validDBInstanceModificationsMessage: nil)
return defaultInstance
}()
}
public extension DescribeValidDBInstanceModificationsResultForDescribeValidDBInstanceModifications {
/**
Default instance of the DescribeValidDBInstanceModificationsResultForDescribeValidDBInstanceModifications structure.
*/
static let __default: RDSModel.DescribeValidDBInstanceModificationsResultForDescribeValidDBInstanceModifications = {
let defaultInstance = RDSModel.DescribeValidDBInstanceModificationsResultForDescribeValidDBInstanceModifications(
describeValidDBInstanceModificationsResult: DescribeValidDBInstanceModificationsResult.__default)
return defaultInstance
}()
}
public extension DomainMembership {
/**
Default instance of the DomainMembership structure.
*/
static let __default: RDSModel.DomainMembership = {
let defaultInstance = RDSModel.DomainMembership(
domain: nil,
fQDN: nil,
iAMRoleName: nil,
status: nil)
return defaultInstance
}()
}
public extension DomainNotFoundFault {
/**
Default instance of the DomainNotFoundFault structure.
*/
static let __default: RDSModel.DomainNotFoundFault = {
let defaultInstance = RDSModel.DomainNotFoundFault()
return defaultInstance
}()
}
public extension DoubleRange {
/**
Default instance of the DoubleRange structure.
*/
static let __default: RDSModel.DoubleRange = {
let defaultInstance = RDSModel.DoubleRange(
from: nil,
to: nil)
return defaultInstance
}()
}
public extension DownloadDBLogFilePortionDetails {
/**
Default instance of the DownloadDBLogFilePortionDetails structure.
*/
static let __default: RDSModel.DownloadDBLogFilePortionDetails = {
let defaultInstance = RDSModel.DownloadDBLogFilePortionDetails(
additionalDataPending: nil,
logFileData: nil,
marker: nil)
return defaultInstance
}()
}
public extension DownloadDBLogFilePortionDetailsForDownloadDBLogFilePortion {
/**
Default instance of the DownloadDBLogFilePortionDetailsForDownloadDBLogFilePortion structure.
*/
static let __default: RDSModel.DownloadDBLogFilePortionDetailsForDownloadDBLogFilePortion = {
let defaultInstance = RDSModel.DownloadDBLogFilePortionDetailsForDownloadDBLogFilePortion(
downloadDBLogFilePortionResult: DownloadDBLogFilePortionDetails.__default)
return defaultInstance
}()
}
public extension DownloadDBLogFilePortionMessage {
/**
Default instance of the DownloadDBLogFilePortionMessage structure.
*/
static let __default: RDSModel.DownloadDBLogFilePortionMessage = {
let defaultInstance = RDSModel.DownloadDBLogFilePortionMessage(
dBInstanceIdentifier: "value",
logFileName: "value",
marker: nil,
numberOfLines: nil)
return defaultInstance
}()
}
public extension EC2SecurityGroup {
/**
Default instance of the EC2SecurityGroup structure.
*/
static let __default: RDSModel.EC2SecurityGroup = {
let defaultInstance = RDSModel.EC2SecurityGroup(
eC2SecurityGroupId: nil,
eC2SecurityGroupName: nil,
eC2SecurityGroupOwnerId: nil,
status: nil)
return defaultInstance
}()
}
public extension Endpoint {
/**
Default instance of the Endpoint structure.
*/
static let __default: RDSModel.Endpoint = {
let defaultInstance = RDSModel.Endpoint(
address: nil,
hostedZoneId: nil,
port: nil)
return defaultInstance
}()
}
public extension EngineDefaults {
/**
Default instance of the EngineDefaults structure.
*/
static let __default: RDSModel.EngineDefaults = {
let defaultInstance = RDSModel.EngineDefaults(
dBParameterGroupFamily: nil,
marker: nil,
parameters: nil)
return defaultInstance
}()
}
public extension Event {
/**
Default instance of the Event structure.
*/
static let __default: RDSModel.Event = {
let defaultInstance = RDSModel.Event(
date: nil,
eventCategories: nil,
message: nil,
sourceArn: nil,
sourceIdentifier: nil,
sourceType: nil)
return defaultInstance
}()
}
public extension EventCategoriesMap {
/**
Default instance of the EventCategoriesMap structure.
*/
static let __default: RDSModel.EventCategoriesMap = {
let defaultInstance = RDSModel.EventCategoriesMap(
eventCategories: nil,
sourceType: nil)
return defaultInstance
}()
}
public extension EventCategoriesMessage {
/**
Default instance of the EventCategoriesMessage structure.
*/
static let __default: RDSModel.EventCategoriesMessage = {
let defaultInstance = RDSModel.EventCategoriesMessage(
eventCategoriesMapList: nil)
return defaultInstance
}()
}
public extension EventCategoriesMessageForDescribeEventCategories {
/**
Default instance of the EventCategoriesMessageForDescribeEventCategories structure.
*/
static let __default: RDSModel.EventCategoriesMessageForDescribeEventCategories = {
let defaultInstance = RDSModel.EventCategoriesMessageForDescribeEventCategories(
describeEventCategoriesResult: EventCategoriesMessage.__default)
return defaultInstance
}()
}
public extension EventSubscription {
/**
Default instance of the EventSubscription structure.
*/
static let __default: RDSModel.EventSubscription = {
let defaultInstance = RDSModel.EventSubscription(
custSubscriptionId: nil,
customerAwsId: nil,
enabled: nil,
eventCategoriesList: nil,
eventSubscriptionArn: nil,
snsTopicArn: nil,
sourceIdsList: nil,
sourceType: nil,
status: nil,
subscriptionCreationTime: nil)
return defaultInstance
}()
}
public extension EventSubscriptionQuotaExceededFault {
/**
Default instance of the EventSubscriptionQuotaExceededFault structure.
*/
static let __default: RDSModel.EventSubscriptionQuotaExceededFault = {
let defaultInstance = RDSModel.EventSubscriptionQuotaExceededFault()
return defaultInstance
}()
}
public extension EventSubscriptionsMessage {
/**
Default instance of the EventSubscriptionsMessage structure.
*/
static let __default: RDSModel.EventSubscriptionsMessage = {
let defaultInstance = RDSModel.EventSubscriptionsMessage(
eventSubscriptionsList: nil,
marker: nil)
return defaultInstance
}()
}
public extension EventSubscriptionsMessageForDescribeEventSubscriptions {
/**
Default instance of the EventSubscriptionsMessageForDescribeEventSubscriptions structure.
*/
static let __default: RDSModel.EventSubscriptionsMessageForDescribeEventSubscriptions = {
let defaultInstance = RDSModel.EventSubscriptionsMessageForDescribeEventSubscriptions(
describeEventSubscriptionsResult: EventSubscriptionsMessage.__default)
return defaultInstance
}()
}
public extension EventsMessage {
/**
Default instance of the EventsMessage structure.
*/
static let __default: RDSModel.EventsMessage = {
let defaultInstance = RDSModel.EventsMessage(
events: nil,
marker: nil)
return defaultInstance
}()
}
public extension EventsMessageForDescribeEvents {
/**
Default instance of the EventsMessageForDescribeEvents structure.
*/
static let __default: RDSModel.EventsMessageForDescribeEvents = {
let defaultInstance = RDSModel.EventsMessageForDescribeEvents(
describeEventsResult: EventsMessage.__default)
return defaultInstance
}()
}
public extension ExportTask {
/**
Default instance of the ExportTask structure.
*/
static let __default: RDSModel.ExportTask = {
let defaultInstance = RDSModel.ExportTask(
exportOnly: nil,
exportTaskIdentifier: nil,
failureCause: nil,
iamRoleArn: nil,
kmsKeyId: nil,
percentProgress: nil,
s3Bucket: nil,
s3Prefix: nil,
snapshotTime: nil,
sourceArn: nil,
status: nil,
taskEndTime: nil,
taskStartTime: nil,
totalExtractedDataInGB: nil,
warningMessage: nil)
return defaultInstance
}()
}
public extension ExportTaskAlreadyExistsFault {
/**
Default instance of the ExportTaskAlreadyExistsFault structure.
*/
static let __default: RDSModel.ExportTaskAlreadyExistsFault = {
let defaultInstance = RDSModel.ExportTaskAlreadyExistsFault()
return defaultInstance
}()
}
public extension ExportTaskForCancelExportTask {
/**
Default instance of the ExportTaskForCancelExportTask structure.
*/
static let __default: RDSModel.ExportTaskForCancelExportTask = {
let defaultInstance = RDSModel.ExportTaskForCancelExportTask(
cancelExportTaskResult: ExportTask.__default)
return defaultInstance
}()
}
public extension ExportTaskForStartExportTask {
/**
Default instance of the ExportTaskForStartExportTask structure.
*/
static let __default: RDSModel.ExportTaskForStartExportTask = {
let defaultInstance = RDSModel.ExportTaskForStartExportTask(
startExportTaskResult: ExportTask.__default)
return defaultInstance
}()
}
public extension ExportTaskNotFoundFault {
/**
Default instance of the ExportTaskNotFoundFault structure.
*/
static let __default: RDSModel.ExportTaskNotFoundFault = {
let defaultInstance = RDSModel.ExportTaskNotFoundFault()
return defaultInstance
}()
}
public extension ExportTasksMessage {
/**
Default instance of the ExportTasksMessage structure.
*/
static let __default: RDSModel.ExportTasksMessage = {
let defaultInstance = RDSModel.ExportTasksMessage(
exportTasks: nil,
marker: nil)
return defaultInstance
}()
}
public extension ExportTasksMessageForDescribeExportTasks {
/**
Default instance of the ExportTasksMessageForDescribeExportTasks structure.
*/
static let __default: RDSModel.ExportTasksMessageForDescribeExportTasks = {
let defaultInstance = RDSModel.ExportTasksMessageForDescribeExportTasks(
describeExportTasksResult: ExportTasksMessage.__default)
return defaultInstance
}()
}
public extension FailoverDBClusterMessage {
/**
Default instance of the FailoverDBClusterMessage structure.
*/
static let __default: RDSModel.FailoverDBClusterMessage = {
let defaultInstance = RDSModel.FailoverDBClusterMessage(
dBClusterIdentifier: "value",
targetDBInstanceIdentifier: nil)
return defaultInstance
}()
}
public extension FailoverDBClusterResult {
/**
Default instance of the FailoverDBClusterResult structure.
*/
static let __default: RDSModel.FailoverDBClusterResult = {
let defaultInstance = RDSModel.FailoverDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension FailoverDBClusterResultForFailoverDBCluster {
/**
Default instance of the FailoverDBClusterResultForFailoverDBCluster structure.
*/
static let __default: RDSModel.FailoverDBClusterResultForFailoverDBCluster = {
let defaultInstance = RDSModel.FailoverDBClusterResultForFailoverDBCluster(
failoverDBClusterResult: FailoverDBClusterResult.__default)
return defaultInstance
}()
}
public extension Filter {
/**
Default instance of the Filter structure.
*/
static let __default: RDSModel.Filter = {
let defaultInstance = RDSModel.Filter(
name: "value",
values: [])
return defaultInstance
}()
}
public extension GlobalCluster {
/**
Default instance of the GlobalCluster structure.
*/
static let __default: RDSModel.GlobalCluster = {
let defaultInstance = RDSModel.GlobalCluster(
databaseName: nil,
deletionProtection: nil,
engine: nil,
engineVersion: nil,
globalClusterArn: nil,
globalClusterIdentifier: nil,
globalClusterMembers: nil,
globalClusterResourceId: nil,
status: nil,
storageEncrypted: nil)
return defaultInstance
}()
}
public extension GlobalClusterAlreadyExistsFault {
/**
Default instance of the GlobalClusterAlreadyExistsFault structure.
*/
static let __default: RDSModel.GlobalClusterAlreadyExistsFault = {
let defaultInstance = RDSModel.GlobalClusterAlreadyExistsFault()
return defaultInstance
}()
}
public extension GlobalClusterMember {
/**
Default instance of the GlobalClusterMember structure.
*/
static let __default: RDSModel.GlobalClusterMember = {
let defaultInstance = RDSModel.GlobalClusterMember(
dBClusterArn: nil,
globalWriteForwardingStatus: nil,
isWriter: nil,
readers: nil)
return defaultInstance
}()
}
public extension GlobalClusterNotFoundFault {
/**
Default instance of the GlobalClusterNotFoundFault structure.
*/
static let __default: RDSModel.GlobalClusterNotFoundFault = {
let defaultInstance = RDSModel.GlobalClusterNotFoundFault()
return defaultInstance
}()
}
public extension GlobalClusterQuotaExceededFault {
/**
Default instance of the GlobalClusterQuotaExceededFault structure.
*/
static let __default: RDSModel.GlobalClusterQuotaExceededFault = {
let defaultInstance = RDSModel.GlobalClusterQuotaExceededFault()
return defaultInstance
}()
}
public extension GlobalClustersMessage {
/**
Default instance of the GlobalClustersMessage structure.
*/
static let __default: RDSModel.GlobalClustersMessage = {
let defaultInstance = RDSModel.GlobalClustersMessage(
globalClusters: nil,
marker: nil)
return defaultInstance
}()
}
public extension GlobalClustersMessageForDescribeGlobalClusters {
/**
Default instance of the GlobalClustersMessageForDescribeGlobalClusters structure.
*/
static let __default: RDSModel.GlobalClustersMessageForDescribeGlobalClusters = {
let defaultInstance = RDSModel.GlobalClustersMessageForDescribeGlobalClusters(
describeGlobalClustersResult: GlobalClustersMessage.__default)
return defaultInstance
}()
}
public extension IPRange {
/**
Default instance of the IPRange structure.
*/
static let __default: RDSModel.IPRange = {
let defaultInstance = RDSModel.IPRange(
cIDRIP: nil,
status: nil)
return defaultInstance
}()
}
public extension IamRoleMissingPermissionsFault {
/**
Default instance of the IamRoleMissingPermissionsFault structure.
*/
static let __default: RDSModel.IamRoleMissingPermissionsFault = {
let defaultInstance = RDSModel.IamRoleMissingPermissionsFault()
return defaultInstance
}()
}
public extension IamRoleNotFoundFault {
/**
Default instance of the IamRoleNotFoundFault structure.
*/
static let __default: RDSModel.IamRoleNotFoundFault = {
let defaultInstance = RDSModel.IamRoleNotFoundFault()
return defaultInstance
}()
}
public extension ImportInstallationMediaMessage {
/**
Default instance of the ImportInstallationMediaMessage structure.
*/
static let __default: RDSModel.ImportInstallationMediaMessage = {
let defaultInstance = RDSModel.ImportInstallationMediaMessage(
customAvailabilityZoneId: "value",
engine: "value",
engineInstallationMediaPath: "value",
engineVersion: "value",
oSInstallationMediaPath: "value")
return defaultInstance
}()
}
public extension InstallationMedia {
/**
Default instance of the InstallationMedia structure.
*/
static let __default: RDSModel.InstallationMedia = {
let defaultInstance = RDSModel.InstallationMedia(
customAvailabilityZoneId: nil,
engine: nil,
engineInstallationMediaPath: nil,
engineVersion: nil,
failureCause: nil,
installationMediaId: nil,
oSInstallationMediaPath: nil,
status: nil)
return defaultInstance
}()
}
public extension InstallationMediaAlreadyExistsFault {
/**
Default instance of the InstallationMediaAlreadyExistsFault structure.
*/
static let __default: RDSModel.InstallationMediaAlreadyExistsFault = {
let defaultInstance = RDSModel.InstallationMediaAlreadyExistsFault()
return defaultInstance
}()
}
public extension InstallationMediaFailureCause {
/**
Default instance of the InstallationMediaFailureCause structure.
*/
static let __default: RDSModel.InstallationMediaFailureCause = {
let defaultInstance = RDSModel.InstallationMediaFailureCause(
message: nil)
return defaultInstance
}()
}
public extension InstallationMediaForDeleteInstallationMedia {
/**
Default instance of the InstallationMediaForDeleteInstallationMedia structure.
*/
static let __default: RDSModel.InstallationMediaForDeleteInstallationMedia = {
let defaultInstance = RDSModel.InstallationMediaForDeleteInstallationMedia(
deleteInstallationMediaResult: InstallationMedia.__default)
return defaultInstance
}()
}
public extension InstallationMediaForImportInstallationMedia {
/**
Default instance of the InstallationMediaForImportInstallationMedia structure.
*/
static let __default: RDSModel.InstallationMediaForImportInstallationMedia = {
let defaultInstance = RDSModel.InstallationMediaForImportInstallationMedia(
importInstallationMediaResult: InstallationMedia.__default)
return defaultInstance
}()
}
public extension InstallationMediaMessage {
/**
Default instance of the InstallationMediaMessage structure.
*/
static let __default: RDSModel.InstallationMediaMessage = {
let defaultInstance = RDSModel.InstallationMediaMessage(
installationMedia: nil,
marker: nil)
return defaultInstance
}()
}
public extension InstallationMediaMessageForDescribeInstallationMedia {
/**
Default instance of the InstallationMediaMessageForDescribeInstallationMedia structure.
*/
static let __default: RDSModel.InstallationMediaMessageForDescribeInstallationMedia = {
let defaultInstance = RDSModel.InstallationMediaMessageForDescribeInstallationMedia(
describeInstallationMediaResult: InstallationMediaMessage.__default)
return defaultInstance
}()
}
public extension InstallationMediaNotFoundFault {
/**
Default instance of the InstallationMediaNotFoundFault structure.
*/
static let __default: RDSModel.InstallationMediaNotFoundFault = {
let defaultInstance = RDSModel.InstallationMediaNotFoundFault()
return defaultInstance
}()
}
public extension InstanceQuotaExceededFault {
/**
Default instance of the InstanceQuotaExceededFault structure.
*/
static let __default: RDSModel.InstanceQuotaExceededFault = {
let defaultInstance = RDSModel.InstanceQuotaExceededFault()
return defaultInstance
}()
}
public extension InsufficientAvailableIPsInSubnetFault {
/**
Default instance of the InsufficientAvailableIPsInSubnetFault structure.
*/
static let __default: RDSModel.InsufficientAvailableIPsInSubnetFault = {
let defaultInstance = RDSModel.InsufficientAvailableIPsInSubnetFault()
return defaultInstance
}()
}
public extension InsufficientDBClusterCapacityFault {
/**
Default instance of the InsufficientDBClusterCapacityFault structure.
*/
static let __default: RDSModel.InsufficientDBClusterCapacityFault = {
let defaultInstance = RDSModel.InsufficientDBClusterCapacityFault()
return defaultInstance
}()
}
public extension InsufficientDBInstanceCapacityFault {
/**
Default instance of the InsufficientDBInstanceCapacityFault structure.
*/
static let __default: RDSModel.InsufficientDBInstanceCapacityFault = {
let defaultInstance = RDSModel.InsufficientDBInstanceCapacityFault()
return defaultInstance
}()
}
public extension InsufficientStorageClusterCapacityFault {
/**
Default instance of the InsufficientStorageClusterCapacityFault structure.
*/
static let __default: RDSModel.InsufficientStorageClusterCapacityFault = {
let defaultInstance = RDSModel.InsufficientStorageClusterCapacityFault()
return defaultInstance
}()
}
public extension InvalidDBClusterCapacityFault {
/**
Default instance of the InvalidDBClusterCapacityFault structure.
*/
static let __default: RDSModel.InvalidDBClusterCapacityFault = {
let defaultInstance = RDSModel.InvalidDBClusterCapacityFault()
return defaultInstance
}()
}
public extension InvalidDBClusterEndpointStateFault {
/**
Default instance of the InvalidDBClusterEndpointStateFault structure.
*/
static let __default: RDSModel.InvalidDBClusterEndpointStateFault = {
let defaultInstance = RDSModel.InvalidDBClusterEndpointStateFault()
return defaultInstance
}()
}
public extension InvalidDBClusterSnapshotStateFault {
/**
Default instance of the InvalidDBClusterSnapshotStateFault structure.
*/
static let __default: RDSModel.InvalidDBClusterSnapshotStateFault = {
let defaultInstance = RDSModel.InvalidDBClusterSnapshotStateFault()
return defaultInstance
}()
}
public extension InvalidDBClusterStateFault {
/**
Default instance of the InvalidDBClusterStateFault structure.
*/
static let __default: RDSModel.InvalidDBClusterStateFault = {
let defaultInstance = RDSModel.InvalidDBClusterStateFault()
return defaultInstance
}()
}
public extension InvalidDBInstanceAutomatedBackupStateFault {
/**
Default instance of the InvalidDBInstanceAutomatedBackupStateFault structure.
*/
static let __default: RDSModel.InvalidDBInstanceAutomatedBackupStateFault = {
let defaultInstance = RDSModel.InvalidDBInstanceAutomatedBackupStateFault()
return defaultInstance
}()
}
public extension InvalidDBInstanceStateFault {
/**
Default instance of the InvalidDBInstanceStateFault structure.
*/
static let __default: RDSModel.InvalidDBInstanceStateFault = {
let defaultInstance = RDSModel.InvalidDBInstanceStateFault()
return defaultInstance
}()
}
public extension InvalidDBParameterGroupStateFault {
/**
Default instance of the InvalidDBParameterGroupStateFault structure.
*/
static let __default: RDSModel.InvalidDBParameterGroupStateFault = {
let defaultInstance = RDSModel.InvalidDBParameterGroupStateFault()
return defaultInstance
}()
}
public extension InvalidDBProxyStateFault {
/**
Default instance of the InvalidDBProxyStateFault structure.
*/
static let __default: RDSModel.InvalidDBProxyStateFault = {
let defaultInstance = RDSModel.InvalidDBProxyStateFault()
return defaultInstance
}()
}
public extension InvalidDBSecurityGroupStateFault {
/**
Default instance of the InvalidDBSecurityGroupStateFault structure.
*/
static let __default: RDSModel.InvalidDBSecurityGroupStateFault = {
let defaultInstance = RDSModel.InvalidDBSecurityGroupStateFault()
return defaultInstance
}()
}
public extension InvalidDBSnapshotStateFault {
/**
Default instance of the InvalidDBSnapshotStateFault structure.
*/
static let __default: RDSModel.InvalidDBSnapshotStateFault = {
let defaultInstance = RDSModel.InvalidDBSnapshotStateFault()
return defaultInstance
}()
}
public extension InvalidDBSubnetGroupFault {
/**
Default instance of the InvalidDBSubnetGroupFault structure.
*/
static let __default: RDSModel.InvalidDBSubnetGroupFault = {
let defaultInstance = RDSModel.InvalidDBSubnetGroupFault()
return defaultInstance
}()
}
public extension InvalidDBSubnetGroupStateFault {
/**
Default instance of the InvalidDBSubnetGroupStateFault structure.
*/
static let __default: RDSModel.InvalidDBSubnetGroupStateFault = {
let defaultInstance = RDSModel.InvalidDBSubnetGroupStateFault()
return defaultInstance
}()
}
public extension InvalidDBSubnetStateFault {
/**
Default instance of the InvalidDBSubnetStateFault structure.
*/
static let __default: RDSModel.InvalidDBSubnetStateFault = {
let defaultInstance = RDSModel.InvalidDBSubnetStateFault()
return defaultInstance
}()
}
public extension InvalidEventSubscriptionStateFault {
/**
Default instance of the InvalidEventSubscriptionStateFault structure.
*/
static let __default: RDSModel.InvalidEventSubscriptionStateFault = {
let defaultInstance = RDSModel.InvalidEventSubscriptionStateFault()
return defaultInstance
}()
}
public extension InvalidExportOnlyFault {
/**
Default instance of the InvalidExportOnlyFault structure.
*/
static let __default: RDSModel.InvalidExportOnlyFault = {
let defaultInstance = RDSModel.InvalidExportOnlyFault()
return defaultInstance
}()
}
public extension InvalidExportSourceStateFault {
/**
Default instance of the InvalidExportSourceStateFault structure.
*/
static let __default: RDSModel.InvalidExportSourceStateFault = {
let defaultInstance = RDSModel.InvalidExportSourceStateFault()
return defaultInstance
}()
}
public extension InvalidExportTaskStateFault {
/**
Default instance of the InvalidExportTaskStateFault structure.
*/
static let __default: RDSModel.InvalidExportTaskStateFault = {
let defaultInstance = RDSModel.InvalidExportTaskStateFault()
return defaultInstance
}()
}
public extension InvalidGlobalClusterStateFault {
/**
Default instance of the InvalidGlobalClusterStateFault structure.
*/
static let __default: RDSModel.InvalidGlobalClusterStateFault = {
let defaultInstance = RDSModel.InvalidGlobalClusterStateFault()
return defaultInstance
}()
}
public extension InvalidOptionGroupStateFault {
/**
Default instance of the InvalidOptionGroupStateFault structure.
*/
static let __default: RDSModel.InvalidOptionGroupStateFault = {
let defaultInstance = RDSModel.InvalidOptionGroupStateFault()
return defaultInstance
}()
}
public extension InvalidRestoreFault {
/**
Default instance of the InvalidRestoreFault structure.
*/
static let __default: RDSModel.InvalidRestoreFault = {
let defaultInstance = RDSModel.InvalidRestoreFault()
return defaultInstance
}()
}
public extension InvalidS3BucketFault {
/**
Default instance of the InvalidS3BucketFault structure.
*/
static let __default: RDSModel.InvalidS3BucketFault = {
let defaultInstance = RDSModel.InvalidS3BucketFault()
return defaultInstance
}()
}
public extension InvalidSubnet {
/**
Default instance of the InvalidSubnet structure.
*/
static let __default: RDSModel.InvalidSubnet = {
let defaultInstance = RDSModel.InvalidSubnet()
return defaultInstance
}()
}
public extension InvalidVPCNetworkStateFault {
/**
Default instance of the InvalidVPCNetworkStateFault structure.
*/
static let __default: RDSModel.InvalidVPCNetworkStateFault = {
let defaultInstance = RDSModel.InvalidVPCNetworkStateFault()
return defaultInstance
}()
}
public extension KMSKeyNotAccessibleFault {
/**
Default instance of the KMSKeyNotAccessibleFault structure.
*/
static let __default: RDSModel.KMSKeyNotAccessibleFault = {
let defaultInstance = RDSModel.KMSKeyNotAccessibleFault()
return defaultInstance
}()
}
public extension ListTagsForResourceMessage {
/**
Default instance of the ListTagsForResourceMessage structure.
*/
static let __default: RDSModel.ListTagsForResourceMessage = {
let defaultInstance = RDSModel.ListTagsForResourceMessage(
filters: nil,
resourceName: "value")
return defaultInstance
}()
}
public extension MinimumEngineVersionPerAllowedValue {
/**
Default instance of the MinimumEngineVersionPerAllowedValue structure.
*/
static let __default: RDSModel.MinimumEngineVersionPerAllowedValue = {
let defaultInstance = RDSModel.MinimumEngineVersionPerAllowedValue(
allowedValue: nil,
minimumEngineVersion: nil)
return defaultInstance
}()
}
public extension ModifyCertificatesMessage {
/**
Default instance of the ModifyCertificatesMessage structure.
*/
static let __default: RDSModel.ModifyCertificatesMessage = {
let defaultInstance = RDSModel.ModifyCertificatesMessage(
certificateIdentifier: nil,
removeCustomerOverride: nil)
return defaultInstance
}()
}
public extension ModifyCertificatesResult {
/**
Default instance of the ModifyCertificatesResult structure.
*/
static let __default: RDSModel.ModifyCertificatesResult = {
let defaultInstance = RDSModel.ModifyCertificatesResult(
certificate: nil)
return defaultInstance
}()
}
public extension ModifyCertificatesResultForModifyCertificates {
/**
Default instance of the ModifyCertificatesResultForModifyCertificates structure.
*/
static let __default: RDSModel.ModifyCertificatesResultForModifyCertificates = {
let defaultInstance = RDSModel.ModifyCertificatesResultForModifyCertificates(
modifyCertificatesResult: ModifyCertificatesResult.__default)
return defaultInstance
}()
}
public extension ModifyCurrentDBClusterCapacityMessage {
/**
Default instance of the ModifyCurrentDBClusterCapacityMessage structure.
*/
static let __default: RDSModel.ModifyCurrentDBClusterCapacityMessage = {
let defaultInstance = RDSModel.ModifyCurrentDBClusterCapacityMessage(
capacity: nil,
dBClusterIdentifier: "value",
secondsBeforeTimeout: nil,
timeoutAction: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterEndpointMessage {
/**
Default instance of the ModifyDBClusterEndpointMessage structure.
*/
static let __default: RDSModel.ModifyDBClusterEndpointMessage = {
let defaultInstance = RDSModel.ModifyDBClusterEndpointMessage(
dBClusterEndpointIdentifier: "value",
endpointType: nil,
excludedMembers: nil,
staticMembers: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterMessage {
/**
Default instance of the ModifyDBClusterMessage structure.
*/
static let __default: RDSModel.ModifyDBClusterMessage = {
let defaultInstance = RDSModel.ModifyDBClusterMessage(
allowMajorVersionUpgrade: nil,
applyImmediately: nil,
backtrackWindow: nil,
backupRetentionPeriod: nil,
cloudwatchLogsExportConfiguration: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: "value",
dBClusterParameterGroupName: nil,
dBInstanceParameterGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableGlobalWriteForwarding: nil,
enableHttpEndpoint: nil,
enableIAMDatabaseAuthentication: nil,
engineVersion: nil,
masterUserPassword: nil,
newDBClusterIdentifier: nil,
optionGroupName: nil,
port: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
scalingConfiguration: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterParameterGroupMessage {
/**
Default instance of the ModifyDBClusterParameterGroupMessage structure.
*/
static let __default: RDSModel.ModifyDBClusterParameterGroupMessage = {
let defaultInstance = RDSModel.ModifyDBClusterParameterGroupMessage(
dBClusterParameterGroupName: "value",
parameters: [])
return defaultInstance
}()
}
public extension ModifyDBClusterResult {
/**
Default instance of the ModifyDBClusterResult structure.
*/
static let __default: RDSModel.ModifyDBClusterResult = {
let defaultInstance = RDSModel.ModifyDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterResultForModifyDBCluster {
/**
Default instance of the ModifyDBClusterResultForModifyDBCluster structure.
*/
static let __default: RDSModel.ModifyDBClusterResultForModifyDBCluster = {
let defaultInstance = RDSModel.ModifyDBClusterResultForModifyDBCluster(
modifyDBClusterResult: ModifyDBClusterResult.__default)
return defaultInstance
}()
}
public extension ModifyDBClusterSnapshotAttributeMessage {
/**
Default instance of the ModifyDBClusterSnapshotAttributeMessage structure.
*/
static let __default: RDSModel.ModifyDBClusterSnapshotAttributeMessage = {
let defaultInstance = RDSModel.ModifyDBClusterSnapshotAttributeMessage(
attributeName: "value",
dBClusterSnapshotIdentifier: "value",
valuesToAdd: nil,
valuesToRemove: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterSnapshotAttributeResult {
/**
Default instance of the ModifyDBClusterSnapshotAttributeResult structure.
*/
static let __default: RDSModel.ModifyDBClusterSnapshotAttributeResult = {
let defaultInstance = RDSModel.ModifyDBClusterSnapshotAttributeResult(
dBClusterSnapshotAttributesResult: nil)
return defaultInstance
}()
}
public extension ModifyDBClusterSnapshotAttributeResultForModifyDBClusterSnapshotAttribute {
/**
Default instance of the ModifyDBClusterSnapshotAttributeResultForModifyDBClusterSnapshotAttribute structure.
*/
static let __default: RDSModel.ModifyDBClusterSnapshotAttributeResultForModifyDBClusterSnapshotAttribute = {
let defaultInstance = RDSModel.ModifyDBClusterSnapshotAttributeResultForModifyDBClusterSnapshotAttribute(
modifyDBClusterSnapshotAttributeResult: ModifyDBClusterSnapshotAttributeResult.__default)
return defaultInstance
}()
}
public extension ModifyDBInstanceMessage {
/**
Default instance of the ModifyDBInstanceMessage structure.
*/
static let __default: RDSModel.ModifyDBInstanceMessage = {
let defaultInstance = RDSModel.ModifyDBInstanceMessage(
allocatedStorage: nil,
allowMajorVersionUpgrade: nil,
applyImmediately: nil,
autoMinorVersionUpgrade: nil,
backupRetentionPeriod: nil,
cACertificateIdentifier: nil,
certificateRotationRestart: nil,
cloudwatchLogsExportConfiguration: nil,
copyTagsToSnapshot: nil,
dBInstanceClass: nil,
dBInstanceIdentifier: "value",
dBParameterGroupName: nil,
dBPortNumber: nil,
dBSecurityGroups: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableIAMDatabaseAuthentication: nil,
enablePerformanceInsights: nil,
engineVersion: nil,
iops: nil,
licenseModel: nil,
masterUserPassword: nil,
maxAllocatedStorage: nil,
monitoringInterval: nil,
monitoringRoleArn: nil,
multiAZ: nil,
newDBInstanceIdentifier: nil,
optionGroupName: nil,
performanceInsightsKMSKeyId: nil,
performanceInsightsRetentionPeriod: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
processorFeatures: nil,
promotionTier: nil,
publiclyAccessible: nil,
replicaMode: nil,
storageType: nil,
tdeCredentialArn: nil,
tdeCredentialPassword: nil,
useDefaultProcessorFeatures: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension ModifyDBInstanceResult {
/**
Default instance of the ModifyDBInstanceResult structure.
*/
static let __default: RDSModel.ModifyDBInstanceResult = {
let defaultInstance = RDSModel.ModifyDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension ModifyDBInstanceResultForModifyDBInstance {
/**
Default instance of the ModifyDBInstanceResultForModifyDBInstance structure.
*/
static let __default: RDSModel.ModifyDBInstanceResultForModifyDBInstance = {
let defaultInstance = RDSModel.ModifyDBInstanceResultForModifyDBInstance(
modifyDBInstanceResult: ModifyDBInstanceResult.__default)
return defaultInstance
}()
}
public extension ModifyDBParameterGroupMessage {
/**
Default instance of the ModifyDBParameterGroupMessage structure.
*/
static let __default: RDSModel.ModifyDBParameterGroupMessage = {
let defaultInstance = RDSModel.ModifyDBParameterGroupMessage(
dBParameterGroupName: "value",
parameters: [])
return defaultInstance
}()
}
public extension ModifyDBProxyRequest {
/**
Default instance of the ModifyDBProxyRequest structure.
*/
static let __default: RDSModel.ModifyDBProxyRequest = {
let defaultInstance = RDSModel.ModifyDBProxyRequest(
auth: nil,
dBProxyName: "value",
debugLogging: nil,
idleClientTimeout: nil,
newDBProxyName: nil,
requireTLS: nil,
roleArn: nil,
securityGroups: nil)
return defaultInstance
}()
}
public extension ModifyDBProxyResponse {
/**
Default instance of the ModifyDBProxyResponse structure.
*/
static let __default: RDSModel.ModifyDBProxyResponse = {
let defaultInstance = RDSModel.ModifyDBProxyResponse(
dBProxy: nil)
return defaultInstance
}()
}
public extension ModifyDBProxyResponseForModifyDBProxy {
/**
Default instance of the ModifyDBProxyResponseForModifyDBProxy structure.
*/
static let __default: RDSModel.ModifyDBProxyResponseForModifyDBProxy = {
let defaultInstance = RDSModel.ModifyDBProxyResponseForModifyDBProxy(
modifyDBProxyResult: ModifyDBProxyResponse.__default)
return defaultInstance
}()
}
public extension ModifyDBProxyTargetGroupRequest {
/**
Default instance of the ModifyDBProxyTargetGroupRequest structure.
*/
static let __default: RDSModel.ModifyDBProxyTargetGroupRequest = {
let defaultInstance = RDSModel.ModifyDBProxyTargetGroupRequest(
connectionPoolConfig: nil,
dBProxyName: "value",
newName: nil,
targetGroupName: "value")
return defaultInstance
}()
}
public extension ModifyDBProxyTargetGroupResponse {
/**
Default instance of the ModifyDBProxyTargetGroupResponse structure.
*/
static let __default: RDSModel.ModifyDBProxyTargetGroupResponse = {
let defaultInstance = RDSModel.ModifyDBProxyTargetGroupResponse(
dBProxyTargetGroup: nil)
return defaultInstance
}()
}
public extension ModifyDBProxyTargetGroupResponseForModifyDBProxyTargetGroup {
/**
Default instance of the ModifyDBProxyTargetGroupResponseForModifyDBProxyTargetGroup structure.
*/
static let __default: RDSModel.ModifyDBProxyTargetGroupResponseForModifyDBProxyTargetGroup = {
let defaultInstance = RDSModel.ModifyDBProxyTargetGroupResponseForModifyDBProxyTargetGroup(
modifyDBProxyTargetGroupResult: ModifyDBProxyTargetGroupResponse.__default)
return defaultInstance
}()
}
public extension ModifyDBSnapshotAttributeMessage {
/**
Default instance of the ModifyDBSnapshotAttributeMessage structure.
*/
static let __default: RDSModel.ModifyDBSnapshotAttributeMessage = {
let defaultInstance = RDSModel.ModifyDBSnapshotAttributeMessage(
attributeName: "value",
dBSnapshotIdentifier: "value",
valuesToAdd: nil,
valuesToRemove: nil)
return defaultInstance
}()
}
public extension ModifyDBSnapshotAttributeResult {
/**
Default instance of the ModifyDBSnapshotAttributeResult structure.
*/
static let __default: RDSModel.ModifyDBSnapshotAttributeResult = {
let defaultInstance = RDSModel.ModifyDBSnapshotAttributeResult(
dBSnapshotAttributesResult: nil)
return defaultInstance
}()
}
public extension ModifyDBSnapshotAttributeResultForModifyDBSnapshotAttribute {
/**
Default instance of the ModifyDBSnapshotAttributeResultForModifyDBSnapshotAttribute structure.
*/
static let __default: RDSModel.ModifyDBSnapshotAttributeResultForModifyDBSnapshotAttribute = {
let defaultInstance = RDSModel.ModifyDBSnapshotAttributeResultForModifyDBSnapshotAttribute(
modifyDBSnapshotAttributeResult: ModifyDBSnapshotAttributeResult.__default)
return defaultInstance
}()
}
public extension ModifyDBSnapshotMessage {
/**
Default instance of the ModifyDBSnapshotMessage structure.
*/
static let __default: RDSModel.ModifyDBSnapshotMessage = {
let defaultInstance = RDSModel.ModifyDBSnapshotMessage(
dBSnapshotIdentifier: "value",
engineVersion: nil,
optionGroupName: nil)
return defaultInstance
}()
}
public extension ModifyDBSnapshotResult {
/**
Default instance of the ModifyDBSnapshotResult structure.
*/
static let __default: RDSModel.ModifyDBSnapshotResult = {
let defaultInstance = RDSModel.ModifyDBSnapshotResult(
dBSnapshot: nil)
return defaultInstance
}()
}
public extension ModifyDBSnapshotResultForModifyDBSnapshot {
/**
Default instance of the ModifyDBSnapshotResultForModifyDBSnapshot structure.
*/
static let __default: RDSModel.ModifyDBSnapshotResultForModifyDBSnapshot = {
let defaultInstance = RDSModel.ModifyDBSnapshotResultForModifyDBSnapshot(
modifyDBSnapshotResult: ModifyDBSnapshotResult.__default)
return defaultInstance
}()
}
public extension ModifyDBSubnetGroupMessage {
/**
Default instance of the ModifyDBSubnetGroupMessage structure.
*/
static let __default: RDSModel.ModifyDBSubnetGroupMessage = {
let defaultInstance = RDSModel.ModifyDBSubnetGroupMessage(
dBSubnetGroupDescription: nil,
dBSubnetGroupName: "value",
subnetIds: [])
return defaultInstance
}()
}
public extension ModifyDBSubnetGroupResult {
/**
Default instance of the ModifyDBSubnetGroupResult structure.
*/
static let __default: RDSModel.ModifyDBSubnetGroupResult = {
let defaultInstance = RDSModel.ModifyDBSubnetGroupResult(
dBSubnetGroup: nil)
return defaultInstance
}()
}
public extension ModifyDBSubnetGroupResultForModifyDBSubnetGroup {
/**
Default instance of the ModifyDBSubnetGroupResultForModifyDBSubnetGroup structure.
*/
static let __default: RDSModel.ModifyDBSubnetGroupResultForModifyDBSubnetGroup = {
let defaultInstance = RDSModel.ModifyDBSubnetGroupResultForModifyDBSubnetGroup(
modifyDBSubnetGroupResult: ModifyDBSubnetGroupResult.__default)
return defaultInstance
}()
}
public extension ModifyEventSubscriptionMessage {
/**
Default instance of the ModifyEventSubscriptionMessage structure.
*/
static let __default: RDSModel.ModifyEventSubscriptionMessage = {
let defaultInstance = RDSModel.ModifyEventSubscriptionMessage(
enabled: nil,
eventCategories: nil,
snsTopicArn: nil,
sourceType: nil,
subscriptionName: "value")
return defaultInstance
}()
}
public extension ModifyEventSubscriptionResult {
/**
Default instance of the ModifyEventSubscriptionResult structure.
*/
static let __default: RDSModel.ModifyEventSubscriptionResult = {
let defaultInstance = RDSModel.ModifyEventSubscriptionResult(
eventSubscription: nil)
return defaultInstance
}()
}
public extension ModifyEventSubscriptionResultForModifyEventSubscription {
/**
Default instance of the ModifyEventSubscriptionResultForModifyEventSubscription structure.
*/
static let __default: RDSModel.ModifyEventSubscriptionResultForModifyEventSubscription = {
let defaultInstance = RDSModel.ModifyEventSubscriptionResultForModifyEventSubscription(
modifyEventSubscriptionResult: ModifyEventSubscriptionResult.__default)
return defaultInstance
}()
}
public extension ModifyGlobalClusterMessage {
/**
Default instance of the ModifyGlobalClusterMessage structure.
*/
static let __default: RDSModel.ModifyGlobalClusterMessage = {
let defaultInstance = RDSModel.ModifyGlobalClusterMessage(
deletionProtection: nil,
globalClusterIdentifier: nil,
newGlobalClusterIdentifier: nil)
return defaultInstance
}()
}
public extension ModifyGlobalClusterResult {
/**
Default instance of the ModifyGlobalClusterResult structure.
*/
static let __default: RDSModel.ModifyGlobalClusterResult = {
let defaultInstance = RDSModel.ModifyGlobalClusterResult(
globalCluster: nil)
return defaultInstance
}()
}
public extension ModifyGlobalClusterResultForModifyGlobalCluster {
/**
Default instance of the ModifyGlobalClusterResultForModifyGlobalCluster structure.
*/
static let __default: RDSModel.ModifyGlobalClusterResultForModifyGlobalCluster = {
let defaultInstance = RDSModel.ModifyGlobalClusterResultForModifyGlobalCluster(
modifyGlobalClusterResult: ModifyGlobalClusterResult.__default)
return defaultInstance
}()
}
public extension ModifyOptionGroupMessage {
/**
Default instance of the ModifyOptionGroupMessage structure.
*/
static let __default: RDSModel.ModifyOptionGroupMessage = {
let defaultInstance = RDSModel.ModifyOptionGroupMessage(
applyImmediately: nil,
optionGroupName: "value",
optionsToInclude: nil,
optionsToRemove: nil)
return defaultInstance
}()
}
public extension ModifyOptionGroupResult {
/**
Default instance of the ModifyOptionGroupResult structure.
*/
static let __default: RDSModel.ModifyOptionGroupResult = {
let defaultInstance = RDSModel.ModifyOptionGroupResult(
optionGroup: nil)
return defaultInstance
}()
}
public extension ModifyOptionGroupResultForModifyOptionGroup {
/**
Default instance of the ModifyOptionGroupResultForModifyOptionGroup structure.
*/
static let __default: RDSModel.ModifyOptionGroupResultForModifyOptionGroup = {
let defaultInstance = RDSModel.ModifyOptionGroupResultForModifyOptionGroup(
modifyOptionGroupResult: ModifyOptionGroupResult.__default)
return defaultInstance
}()
}
public extension Option {
/**
Default instance of the Option structure.
*/
static let __default: RDSModel.Option = {
let defaultInstance = RDSModel.Option(
dBSecurityGroupMemberships: nil,
optionDescription: nil,
optionName: nil,
optionSettings: nil,
optionVersion: nil,
permanent: nil,
persistent: nil,
port: nil,
vpcSecurityGroupMemberships: nil)
return defaultInstance
}()
}
public extension OptionConfiguration {
/**
Default instance of the OptionConfiguration structure.
*/
static let __default: RDSModel.OptionConfiguration = {
let defaultInstance = RDSModel.OptionConfiguration(
dBSecurityGroupMemberships: nil,
optionName: "value",
optionSettings: nil,
optionVersion: nil,
port: nil,
vpcSecurityGroupMemberships: nil)
return defaultInstance
}()
}
public extension OptionGroup {
/**
Default instance of the OptionGroup structure.
*/
static let __default: RDSModel.OptionGroup = {
let defaultInstance = RDSModel.OptionGroup(
allowsVpcAndNonVpcInstanceMemberships: nil,
engineName: nil,
majorEngineVersion: nil,
optionGroupArn: nil,
optionGroupDescription: nil,
optionGroupName: nil,
options: nil,
vpcId: nil)
return defaultInstance
}()
}
public extension OptionGroupAlreadyExistsFault {
/**
Default instance of the OptionGroupAlreadyExistsFault structure.
*/
static let __default: RDSModel.OptionGroupAlreadyExistsFault = {
let defaultInstance = RDSModel.OptionGroupAlreadyExistsFault()
return defaultInstance
}()
}
public extension OptionGroupMembership {
/**
Default instance of the OptionGroupMembership structure.
*/
static let __default: RDSModel.OptionGroupMembership = {
let defaultInstance = RDSModel.OptionGroupMembership(
optionGroupName: nil,
status: nil)
return defaultInstance
}()
}
public extension OptionGroupNotFoundFault {
/**
Default instance of the OptionGroupNotFoundFault structure.
*/
static let __default: RDSModel.OptionGroupNotFoundFault = {
let defaultInstance = RDSModel.OptionGroupNotFoundFault()
return defaultInstance
}()
}
public extension OptionGroupOption {
/**
Default instance of the OptionGroupOption structure.
*/
static let __default: RDSModel.OptionGroupOption = {
let defaultInstance = RDSModel.OptionGroupOption(
defaultPort: nil,
description: nil,
engineName: nil,
majorEngineVersion: nil,
minimumRequiredMinorEngineVersion: nil,
name: nil,
optionGroupOptionSettings: nil,
optionGroupOptionVersions: nil,
optionsConflictsWith: nil,
optionsDependedOn: nil,
permanent: nil,
persistent: nil,
portRequired: nil,
requiresAutoMinorEngineVersionUpgrade: nil,
supportsOptionVersionDowngrade: nil,
vpcOnly: nil)
return defaultInstance
}()
}
public extension OptionGroupOptionSetting {
/**
Default instance of the OptionGroupOptionSetting structure.
*/
static let __default: RDSModel.OptionGroupOptionSetting = {
let defaultInstance = RDSModel.OptionGroupOptionSetting(
allowedValues: nil,
applyType: nil,
defaultValue: nil,
isModifiable: nil,
isRequired: nil,
minimumEngineVersionPerAllowedValue: nil,
settingDescription: nil,
settingName: nil)
return defaultInstance
}()
}
public extension OptionGroupOptionsMessage {
/**
Default instance of the OptionGroupOptionsMessage structure.
*/
static let __default: RDSModel.OptionGroupOptionsMessage = {
let defaultInstance = RDSModel.OptionGroupOptionsMessage(
marker: nil,
optionGroupOptions: nil)
return defaultInstance
}()
}
public extension OptionGroupOptionsMessageForDescribeOptionGroupOptions {
/**
Default instance of the OptionGroupOptionsMessageForDescribeOptionGroupOptions structure.
*/
static let __default: RDSModel.OptionGroupOptionsMessageForDescribeOptionGroupOptions = {
let defaultInstance = RDSModel.OptionGroupOptionsMessageForDescribeOptionGroupOptions(
describeOptionGroupOptionsResult: OptionGroupOptionsMessage.__default)
return defaultInstance
}()
}
public extension OptionGroupQuotaExceededFault {
/**
Default instance of the OptionGroupQuotaExceededFault structure.
*/
static let __default: RDSModel.OptionGroupQuotaExceededFault = {
let defaultInstance = RDSModel.OptionGroupQuotaExceededFault()
return defaultInstance
}()
}
public extension OptionGroups {
/**
Default instance of the OptionGroups structure.
*/
static let __default: RDSModel.OptionGroups = {
let defaultInstance = RDSModel.OptionGroups(
marker: nil,
optionGroupsList: nil)
return defaultInstance
}()
}
public extension OptionGroupsForDescribeOptionGroups {
/**
Default instance of the OptionGroupsForDescribeOptionGroups structure.
*/
static let __default: RDSModel.OptionGroupsForDescribeOptionGroups = {
let defaultInstance = RDSModel.OptionGroupsForDescribeOptionGroups(
describeOptionGroupsResult: OptionGroups.__default)
return defaultInstance
}()
}
public extension OptionSetting {
/**
Default instance of the OptionSetting structure.
*/
static let __default: RDSModel.OptionSetting = {
let defaultInstance = RDSModel.OptionSetting(
allowedValues: nil,
applyType: nil,
dataType: nil,
defaultValue: nil,
description: nil,
isCollection: nil,
isModifiable: nil,
name: nil,
value: nil)
return defaultInstance
}()
}
public extension OptionVersion {
/**
Default instance of the OptionVersion structure.
*/
static let __default: RDSModel.OptionVersion = {
let defaultInstance = RDSModel.OptionVersion(
isDefault: nil,
version: nil)
return defaultInstance
}()
}
public extension OrderableDBInstanceOption {
/**
Default instance of the OrderableDBInstanceOption structure.
*/
static let __default: RDSModel.OrderableDBInstanceOption = {
let defaultInstance = RDSModel.OrderableDBInstanceOption(
availabilityZoneGroup: nil,
availabilityZones: nil,
availableProcessorFeatures: nil,
dBInstanceClass: nil,
engine: nil,
engineVersion: nil,
licenseModel: nil,
maxIopsPerDbInstance: nil,
maxIopsPerGib: nil,
maxStorageSize: nil,
minIopsPerDbInstance: nil,
minIopsPerGib: nil,
minStorageSize: nil,
multiAZCapable: nil,
outpostCapable: nil,
readReplicaCapable: nil,
storageType: nil,
supportedEngineModes: nil,
supportsEnhancedMonitoring: nil,
supportsGlobalDatabases: nil,
supportsIAMDatabaseAuthentication: nil,
supportsIops: nil,
supportsKerberosAuthentication: nil,
supportsPerformanceInsights: nil,
supportsStorageAutoscaling: nil,
supportsStorageEncryption: nil,
vpc: nil)
return defaultInstance
}()
}
public extension OrderableDBInstanceOptionsMessage {
/**
Default instance of the OrderableDBInstanceOptionsMessage structure.
*/
static let __default: RDSModel.OrderableDBInstanceOptionsMessage = {
let defaultInstance = RDSModel.OrderableDBInstanceOptionsMessage(
marker: nil,
orderableDBInstanceOptions: nil)
return defaultInstance
}()
}
public extension OrderableDBInstanceOptionsMessageForDescribeOrderableDBInstanceOptions {
/**
Default instance of the OrderableDBInstanceOptionsMessageForDescribeOrderableDBInstanceOptions structure.
*/
static let __default: RDSModel.OrderableDBInstanceOptionsMessageForDescribeOrderableDBInstanceOptions = {
let defaultInstance = RDSModel.OrderableDBInstanceOptionsMessageForDescribeOrderableDBInstanceOptions(
describeOrderableDBInstanceOptionsResult: OrderableDBInstanceOptionsMessage.__default)
return defaultInstance
}()
}
public extension Outpost {
/**
Default instance of the Outpost structure.
*/
static let __default: RDSModel.Outpost = {
let defaultInstance = RDSModel.Outpost(
arn: nil)
return defaultInstance
}()
}
public extension Parameter {
/**
Default instance of the Parameter structure.
*/
static let __default: RDSModel.Parameter = {
let defaultInstance = RDSModel.Parameter(
allowedValues: nil,
applyMethod: nil,
applyType: nil,
dataType: nil,
description: nil,
isModifiable: nil,
minimumEngineVersion: nil,
parameterName: nil,
parameterValue: nil,
source: nil,
supportedEngineModes: nil)
return defaultInstance
}()
}
public extension PendingCloudwatchLogsExports {
/**
Default instance of the PendingCloudwatchLogsExports structure.
*/
static let __default: RDSModel.PendingCloudwatchLogsExports = {
let defaultInstance = RDSModel.PendingCloudwatchLogsExports(
logTypesToDisable: nil,
logTypesToEnable: nil)
return defaultInstance
}()
}
public extension PendingMaintenanceAction {
/**
Default instance of the PendingMaintenanceAction structure.
*/
static let __default: RDSModel.PendingMaintenanceAction = {
let defaultInstance = RDSModel.PendingMaintenanceAction(
action: nil,
autoAppliedAfterDate: nil,
currentApplyDate: nil,
description: nil,
forcedApplyDate: nil,
optInStatus: nil)
return defaultInstance
}()
}
public extension PendingMaintenanceActionsMessage {
/**
Default instance of the PendingMaintenanceActionsMessage structure.
*/
static let __default: RDSModel.PendingMaintenanceActionsMessage = {
let defaultInstance = RDSModel.PendingMaintenanceActionsMessage(
marker: nil,
pendingMaintenanceActions: nil)
return defaultInstance
}()
}
public extension PendingMaintenanceActionsMessageForDescribePendingMaintenanceActions {
/**
Default instance of the PendingMaintenanceActionsMessageForDescribePendingMaintenanceActions structure.
*/
static let __default: RDSModel.PendingMaintenanceActionsMessageForDescribePendingMaintenanceActions = {
let defaultInstance = RDSModel.PendingMaintenanceActionsMessageForDescribePendingMaintenanceActions(
describePendingMaintenanceActionsResult: PendingMaintenanceActionsMessage.__default)
return defaultInstance
}()
}
public extension PendingModifiedValues {
/**
Default instance of the PendingModifiedValues structure.
*/
static let __default: RDSModel.PendingModifiedValues = {
let defaultInstance = RDSModel.PendingModifiedValues(
allocatedStorage: nil,
backupRetentionPeriod: nil,
cACertificateIdentifier: nil,
dBInstanceClass: nil,
dBInstanceIdentifier: nil,
dBSubnetGroupName: nil,
engineVersion: nil,
iops: nil,
licenseModel: nil,
masterUserPassword: nil,
multiAZ: nil,
pendingCloudwatchLogsExports: nil,
port: nil,
processorFeatures: nil,
storageType: nil)
return defaultInstance
}()
}
public extension PointInTimeRestoreNotEnabledFault {
/**
Default instance of the PointInTimeRestoreNotEnabledFault structure.
*/
static let __default: RDSModel.PointInTimeRestoreNotEnabledFault = {
let defaultInstance = RDSModel.PointInTimeRestoreNotEnabledFault()
return defaultInstance
}()
}
public extension ProcessorFeature {
/**
Default instance of the ProcessorFeature structure.
*/
static let __default: RDSModel.ProcessorFeature = {
let defaultInstance = RDSModel.ProcessorFeature(
name: nil,
value: nil)
return defaultInstance
}()
}
public extension PromoteReadReplicaDBClusterMessage {
/**
Default instance of the PromoteReadReplicaDBClusterMessage structure.
*/
static let __default: RDSModel.PromoteReadReplicaDBClusterMessage = {
let defaultInstance = RDSModel.PromoteReadReplicaDBClusterMessage(
dBClusterIdentifier: "value")
return defaultInstance
}()
}
public extension PromoteReadReplicaDBClusterResult {
/**
Default instance of the PromoteReadReplicaDBClusterResult structure.
*/
static let __default: RDSModel.PromoteReadReplicaDBClusterResult = {
let defaultInstance = RDSModel.PromoteReadReplicaDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension PromoteReadReplicaDBClusterResultForPromoteReadReplicaDBCluster {
/**
Default instance of the PromoteReadReplicaDBClusterResultForPromoteReadReplicaDBCluster structure.
*/
static let __default: RDSModel.PromoteReadReplicaDBClusterResultForPromoteReadReplicaDBCluster = {
let defaultInstance = RDSModel.PromoteReadReplicaDBClusterResultForPromoteReadReplicaDBCluster(
promoteReadReplicaDBClusterResult: PromoteReadReplicaDBClusterResult.__default)
return defaultInstance
}()
}
public extension PromoteReadReplicaMessage {
/**
Default instance of the PromoteReadReplicaMessage structure.
*/
static let __default: RDSModel.PromoteReadReplicaMessage = {
let defaultInstance = RDSModel.PromoteReadReplicaMessage(
backupRetentionPeriod: nil,
dBInstanceIdentifier: "value",
preferredBackupWindow: nil)
return defaultInstance
}()
}
public extension PromoteReadReplicaResult {
/**
Default instance of the PromoteReadReplicaResult structure.
*/
static let __default: RDSModel.PromoteReadReplicaResult = {
let defaultInstance = RDSModel.PromoteReadReplicaResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension PromoteReadReplicaResultForPromoteReadReplica {
/**
Default instance of the PromoteReadReplicaResultForPromoteReadReplica structure.
*/
static let __default: RDSModel.PromoteReadReplicaResultForPromoteReadReplica = {
let defaultInstance = RDSModel.PromoteReadReplicaResultForPromoteReadReplica(
promoteReadReplicaResult: PromoteReadReplicaResult.__default)
return defaultInstance
}()
}
public extension ProvisionedIopsNotAvailableInAZFault {
/**
Default instance of the ProvisionedIopsNotAvailableInAZFault structure.
*/
static let __default: RDSModel.ProvisionedIopsNotAvailableInAZFault = {
let defaultInstance = RDSModel.ProvisionedIopsNotAvailableInAZFault()
return defaultInstance
}()
}
public extension PurchaseReservedDBInstancesOfferingMessage {
/**
Default instance of the PurchaseReservedDBInstancesOfferingMessage structure.
*/
static let __default: RDSModel.PurchaseReservedDBInstancesOfferingMessage = {
let defaultInstance = RDSModel.PurchaseReservedDBInstancesOfferingMessage(
dBInstanceCount: nil,
reservedDBInstanceId: nil,
reservedDBInstancesOfferingId: "value",
tags: nil)
return defaultInstance
}()
}
public extension PurchaseReservedDBInstancesOfferingResult {
/**
Default instance of the PurchaseReservedDBInstancesOfferingResult structure.
*/
static let __default: RDSModel.PurchaseReservedDBInstancesOfferingResult = {
let defaultInstance = RDSModel.PurchaseReservedDBInstancesOfferingResult(
reservedDBInstance: nil)
return defaultInstance
}()
}
public extension PurchaseReservedDBInstancesOfferingResultForPurchaseReservedDBInstancesOffering {
/**
Default instance of the PurchaseReservedDBInstancesOfferingResultForPurchaseReservedDBInstancesOffering structure.
*/
static let __default: RDSModel.PurchaseReservedDBInstancesOfferingResultForPurchaseReservedDBInstancesOffering = {
let defaultInstance = RDSModel.PurchaseReservedDBInstancesOfferingResultForPurchaseReservedDBInstancesOffering(
purchaseReservedDBInstancesOfferingResult: PurchaseReservedDBInstancesOfferingResult.__default)
return defaultInstance
}()
}
public extension Range {
/**
Default instance of the Range structure.
*/
static let __default: RDSModel.Range = {
let defaultInstance = RDSModel.Range(
from: nil,
step: nil,
to: nil)
return defaultInstance
}()
}
public extension RebootDBInstanceMessage {
/**
Default instance of the RebootDBInstanceMessage structure.
*/
static let __default: RDSModel.RebootDBInstanceMessage = {
let defaultInstance = RDSModel.RebootDBInstanceMessage(
dBInstanceIdentifier: "value",
forceFailover: nil)
return defaultInstance
}()
}
public extension RebootDBInstanceResult {
/**
Default instance of the RebootDBInstanceResult structure.
*/
static let __default: RDSModel.RebootDBInstanceResult = {
let defaultInstance = RDSModel.RebootDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension RebootDBInstanceResultForRebootDBInstance {
/**
Default instance of the RebootDBInstanceResultForRebootDBInstance structure.
*/
static let __default: RDSModel.RebootDBInstanceResultForRebootDBInstance = {
let defaultInstance = RDSModel.RebootDBInstanceResultForRebootDBInstance(
rebootDBInstanceResult: RebootDBInstanceResult.__default)
return defaultInstance
}()
}
public extension RecurringCharge {
/**
Default instance of the RecurringCharge structure.
*/
static let __default: RDSModel.RecurringCharge = {
let defaultInstance = RDSModel.RecurringCharge(
recurringChargeAmount: nil,
recurringChargeFrequency: nil)
return defaultInstance
}()
}
public extension RegisterDBProxyTargetsRequest {
/**
Default instance of the RegisterDBProxyTargetsRequest structure.
*/
static let __default: RDSModel.RegisterDBProxyTargetsRequest = {
let defaultInstance = RDSModel.RegisterDBProxyTargetsRequest(
dBClusterIdentifiers: nil,
dBInstanceIdentifiers: nil,
dBProxyName: "value",
targetGroupName: nil)
return defaultInstance
}()
}
public extension RegisterDBProxyTargetsResponse {
/**
Default instance of the RegisterDBProxyTargetsResponse structure.
*/
static let __default: RDSModel.RegisterDBProxyTargetsResponse = {
let defaultInstance = RDSModel.RegisterDBProxyTargetsResponse(
dBProxyTargets: nil)
return defaultInstance
}()
}
public extension RegisterDBProxyTargetsResponseForRegisterDBProxyTargets {
/**
Default instance of the RegisterDBProxyTargetsResponseForRegisterDBProxyTargets structure.
*/
static let __default: RDSModel.RegisterDBProxyTargetsResponseForRegisterDBProxyTargets = {
let defaultInstance = RDSModel.RegisterDBProxyTargetsResponseForRegisterDBProxyTargets(
registerDBProxyTargetsResult: RegisterDBProxyTargetsResponse.__default)
return defaultInstance
}()
}
public extension RemoveFromGlobalClusterMessage {
/**
Default instance of the RemoveFromGlobalClusterMessage structure.
*/
static let __default: RDSModel.RemoveFromGlobalClusterMessage = {
let defaultInstance = RDSModel.RemoveFromGlobalClusterMessage(
dbClusterIdentifier: nil,
globalClusterIdentifier: nil)
return defaultInstance
}()
}
public extension RemoveFromGlobalClusterResult {
/**
Default instance of the RemoveFromGlobalClusterResult structure.
*/
static let __default: RDSModel.RemoveFromGlobalClusterResult = {
let defaultInstance = RDSModel.RemoveFromGlobalClusterResult(
globalCluster: nil)
return defaultInstance
}()
}
public extension RemoveFromGlobalClusterResultForRemoveFromGlobalCluster {
/**
Default instance of the RemoveFromGlobalClusterResultForRemoveFromGlobalCluster structure.
*/
static let __default: RDSModel.RemoveFromGlobalClusterResultForRemoveFromGlobalCluster = {
let defaultInstance = RDSModel.RemoveFromGlobalClusterResultForRemoveFromGlobalCluster(
removeFromGlobalClusterResult: RemoveFromGlobalClusterResult.__default)
return defaultInstance
}()
}
public extension RemoveRoleFromDBClusterMessage {
/**
Default instance of the RemoveRoleFromDBClusterMessage structure.
*/
static let __default: RDSModel.RemoveRoleFromDBClusterMessage = {
let defaultInstance = RDSModel.RemoveRoleFromDBClusterMessage(
dBClusterIdentifier: "value",
featureName: nil,
roleArn: "value")
return defaultInstance
}()
}
public extension RemoveRoleFromDBInstanceMessage {
/**
Default instance of the RemoveRoleFromDBInstanceMessage structure.
*/
static let __default: RDSModel.RemoveRoleFromDBInstanceMessage = {
let defaultInstance = RDSModel.RemoveRoleFromDBInstanceMessage(
dBInstanceIdentifier: "value",
featureName: "value",
roleArn: "value")
return defaultInstance
}()
}
public extension RemoveSourceIdentifierFromSubscriptionMessage {
/**
Default instance of the RemoveSourceIdentifierFromSubscriptionMessage structure.
*/
static let __default: RDSModel.RemoveSourceIdentifierFromSubscriptionMessage = {
let defaultInstance = RDSModel.RemoveSourceIdentifierFromSubscriptionMessage(
sourceIdentifier: "value",
subscriptionName: "value")
return defaultInstance
}()
}
public extension RemoveSourceIdentifierFromSubscriptionResult {
/**
Default instance of the RemoveSourceIdentifierFromSubscriptionResult structure.
*/
static let __default: RDSModel.RemoveSourceIdentifierFromSubscriptionResult = {
let defaultInstance = RDSModel.RemoveSourceIdentifierFromSubscriptionResult(
eventSubscription: nil)
return defaultInstance
}()
}
public extension RemoveSourceIdentifierFromSubscriptionResultForRemoveSourceIdentifierFromSubscription {
/**
Default instance of the RemoveSourceIdentifierFromSubscriptionResultForRemoveSourceIdentifierFromSubscription structure.
*/
static let __default: RDSModel.RemoveSourceIdentifierFromSubscriptionResultForRemoveSourceIdentifierFromSubscription = {
let defaultInstance = RDSModel.RemoveSourceIdentifierFromSubscriptionResultForRemoveSourceIdentifierFromSubscription(
removeSourceIdentifierFromSubscriptionResult: RemoveSourceIdentifierFromSubscriptionResult.__default)
return defaultInstance
}()
}
public extension RemoveTagsFromResourceMessage {
/**
Default instance of the RemoveTagsFromResourceMessage structure.
*/
static let __default: RDSModel.RemoveTagsFromResourceMessage = {
let defaultInstance = RDSModel.RemoveTagsFromResourceMessage(
resourceName: "value",
tagKeys: [])
return defaultInstance
}()
}
public extension ReservedDBInstance {
/**
Default instance of the ReservedDBInstance structure.
*/
static let __default: RDSModel.ReservedDBInstance = {
let defaultInstance = RDSModel.ReservedDBInstance(
currencyCode: nil,
dBInstanceClass: nil,
dBInstanceCount: nil,
duration: nil,
fixedPrice: nil,
leaseId: nil,
multiAZ: nil,
offeringType: nil,
productDescription: nil,
recurringCharges: nil,
reservedDBInstanceArn: nil,
reservedDBInstanceId: nil,
reservedDBInstancesOfferingId: nil,
startTime: nil,
state: nil,
usagePrice: nil)
return defaultInstance
}()
}
public extension ReservedDBInstanceAlreadyExistsFault {
/**
Default instance of the ReservedDBInstanceAlreadyExistsFault structure.
*/
static let __default: RDSModel.ReservedDBInstanceAlreadyExistsFault = {
let defaultInstance = RDSModel.ReservedDBInstanceAlreadyExistsFault()
return defaultInstance
}()
}
public extension ReservedDBInstanceMessage {
/**
Default instance of the ReservedDBInstanceMessage structure.
*/
static let __default: RDSModel.ReservedDBInstanceMessage = {
let defaultInstance = RDSModel.ReservedDBInstanceMessage(
marker: nil,
reservedDBInstances: nil)
return defaultInstance
}()
}
public extension ReservedDBInstanceMessageForDescribeReservedDBInstances {
/**
Default instance of the ReservedDBInstanceMessageForDescribeReservedDBInstances structure.
*/
static let __default: RDSModel.ReservedDBInstanceMessageForDescribeReservedDBInstances = {
let defaultInstance = RDSModel.ReservedDBInstanceMessageForDescribeReservedDBInstances(
describeReservedDBInstancesResult: ReservedDBInstanceMessage.__default)
return defaultInstance
}()
}
public extension ReservedDBInstanceNotFoundFault {
/**
Default instance of the ReservedDBInstanceNotFoundFault structure.
*/
static let __default: RDSModel.ReservedDBInstanceNotFoundFault = {
let defaultInstance = RDSModel.ReservedDBInstanceNotFoundFault()
return defaultInstance
}()
}
public extension ReservedDBInstanceQuotaExceededFault {
/**
Default instance of the ReservedDBInstanceQuotaExceededFault structure.
*/
static let __default: RDSModel.ReservedDBInstanceQuotaExceededFault = {
let defaultInstance = RDSModel.ReservedDBInstanceQuotaExceededFault()
return defaultInstance
}()
}
public extension ReservedDBInstancesOffering {
/**
Default instance of the ReservedDBInstancesOffering structure.
*/
static let __default: RDSModel.ReservedDBInstancesOffering = {
let defaultInstance = RDSModel.ReservedDBInstancesOffering(
currencyCode: nil,
dBInstanceClass: nil,
duration: nil,
fixedPrice: nil,
multiAZ: nil,
offeringType: nil,
productDescription: nil,
recurringCharges: nil,
reservedDBInstancesOfferingId: nil,
usagePrice: nil)
return defaultInstance
}()
}
public extension ReservedDBInstancesOfferingMessage {
/**
Default instance of the ReservedDBInstancesOfferingMessage structure.
*/
static let __default: RDSModel.ReservedDBInstancesOfferingMessage = {
let defaultInstance = RDSModel.ReservedDBInstancesOfferingMessage(
marker: nil,
reservedDBInstancesOfferings: nil)
return defaultInstance
}()
}
public extension ReservedDBInstancesOfferingMessageForDescribeReservedDBInstancesOfferings {
/**
Default instance of the ReservedDBInstancesOfferingMessageForDescribeReservedDBInstancesOfferings structure.
*/
static let __default: RDSModel.ReservedDBInstancesOfferingMessageForDescribeReservedDBInstancesOfferings = {
let defaultInstance = RDSModel.ReservedDBInstancesOfferingMessageForDescribeReservedDBInstancesOfferings(
describeReservedDBInstancesOfferingsResult: ReservedDBInstancesOfferingMessage.__default)
return defaultInstance
}()
}
public extension ReservedDBInstancesOfferingNotFoundFault {
/**
Default instance of the ReservedDBInstancesOfferingNotFoundFault structure.
*/
static let __default: RDSModel.ReservedDBInstancesOfferingNotFoundFault = {
let defaultInstance = RDSModel.ReservedDBInstancesOfferingNotFoundFault()
return defaultInstance
}()
}
public extension ResetDBClusterParameterGroupMessage {
/**
Default instance of the ResetDBClusterParameterGroupMessage structure.
*/
static let __default: RDSModel.ResetDBClusterParameterGroupMessage = {
let defaultInstance = RDSModel.ResetDBClusterParameterGroupMessage(
dBClusterParameterGroupName: "value",
parameters: nil,
resetAllParameters: nil)
return defaultInstance
}()
}
public extension ResetDBParameterGroupMessage {
/**
Default instance of the ResetDBParameterGroupMessage structure.
*/
static let __default: RDSModel.ResetDBParameterGroupMessage = {
let defaultInstance = RDSModel.ResetDBParameterGroupMessage(
dBParameterGroupName: "value",
parameters: nil,
resetAllParameters: nil)
return defaultInstance
}()
}
public extension ResourceNotFoundFault {
/**
Default instance of the ResourceNotFoundFault structure.
*/
static let __default: RDSModel.ResourceNotFoundFault = {
let defaultInstance = RDSModel.ResourceNotFoundFault()
return defaultInstance
}()
}
public extension ResourcePendingMaintenanceActions {
/**
Default instance of the ResourcePendingMaintenanceActions structure.
*/
static let __default: RDSModel.ResourcePendingMaintenanceActions = {
let defaultInstance = RDSModel.ResourcePendingMaintenanceActions(
pendingMaintenanceActionDetails: nil,
resourceIdentifier: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterFromS3Message {
/**
Default instance of the RestoreDBClusterFromS3Message structure.
*/
static let __default: RDSModel.RestoreDBClusterFromS3Message = {
let defaultInstance = RDSModel.RestoreDBClusterFromS3Message(
availabilityZones: nil,
backtrackWindow: nil,
backupRetentionPeriod: nil,
characterSetName: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: "value",
dBClusterParameterGroupName: nil,
dBSubnetGroupName: nil,
databaseName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
engine: "value",
engineVersion: nil,
kmsKeyId: nil,
masterUserPassword: "value",
masterUsername: "value",
optionGroupName: nil,
port: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
s3BucketName: "value",
s3IngestionRoleArn: "value",
s3Prefix: nil,
sourceEngine: "value",
sourceEngineVersion: "value",
storageEncrypted: nil,
tags: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterFromS3Result {
/**
Default instance of the RestoreDBClusterFromS3Result structure.
*/
static let __default: RDSModel.RestoreDBClusterFromS3Result = {
let defaultInstance = RDSModel.RestoreDBClusterFromS3Result(
dBCluster: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterFromS3ResultForRestoreDBClusterFromS3 {
/**
Default instance of the RestoreDBClusterFromS3ResultForRestoreDBClusterFromS3 structure.
*/
static let __default: RDSModel.RestoreDBClusterFromS3ResultForRestoreDBClusterFromS3 = {
let defaultInstance = RDSModel.RestoreDBClusterFromS3ResultForRestoreDBClusterFromS3(
restoreDBClusterFromS3Result: RestoreDBClusterFromS3Result.__default)
return defaultInstance
}()
}
public extension RestoreDBClusterFromSnapshotMessage {
/**
Default instance of the RestoreDBClusterFromSnapshotMessage structure.
*/
static let __default: RDSModel.RestoreDBClusterFromSnapshotMessage = {
let defaultInstance = RDSModel.RestoreDBClusterFromSnapshotMessage(
availabilityZones: nil,
backtrackWindow: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: "value",
dBClusterParameterGroupName: nil,
dBSubnetGroupName: nil,
databaseName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
engine: "value",
engineMode: nil,
engineVersion: nil,
kmsKeyId: nil,
optionGroupName: nil,
port: nil,
scalingConfiguration: nil,
snapshotIdentifier: "value",
tags: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterFromSnapshotResult {
/**
Default instance of the RestoreDBClusterFromSnapshotResult structure.
*/
static let __default: RDSModel.RestoreDBClusterFromSnapshotResult = {
let defaultInstance = RDSModel.RestoreDBClusterFromSnapshotResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterFromSnapshotResultForRestoreDBClusterFromSnapshot {
/**
Default instance of the RestoreDBClusterFromSnapshotResultForRestoreDBClusterFromSnapshot structure.
*/
static let __default: RDSModel.RestoreDBClusterFromSnapshotResultForRestoreDBClusterFromSnapshot = {
let defaultInstance = RDSModel.RestoreDBClusterFromSnapshotResultForRestoreDBClusterFromSnapshot(
restoreDBClusterFromSnapshotResult: RestoreDBClusterFromSnapshotResult.__default)
return defaultInstance
}()
}
public extension RestoreDBClusterToPointInTimeMessage {
/**
Default instance of the RestoreDBClusterToPointInTimeMessage structure.
*/
static let __default: RDSModel.RestoreDBClusterToPointInTimeMessage = {
let defaultInstance = RDSModel.RestoreDBClusterToPointInTimeMessage(
backtrackWindow: nil,
copyTagsToSnapshot: nil,
dBClusterIdentifier: "value",
dBClusterParameterGroupName: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
kmsKeyId: nil,
optionGroupName: nil,
port: nil,
restoreToTime: nil,
restoreType: nil,
sourceDBClusterIdentifier: "value",
tags: nil,
useLatestRestorableTime: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterToPointInTimeResult {
/**
Default instance of the RestoreDBClusterToPointInTimeResult structure.
*/
static let __default: RDSModel.RestoreDBClusterToPointInTimeResult = {
let defaultInstance = RDSModel.RestoreDBClusterToPointInTimeResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension RestoreDBClusterToPointInTimeResultForRestoreDBClusterToPointInTime {
/**
Default instance of the RestoreDBClusterToPointInTimeResultForRestoreDBClusterToPointInTime structure.
*/
static let __default: RDSModel.RestoreDBClusterToPointInTimeResultForRestoreDBClusterToPointInTime = {
let defaultInstance = RDSModel.RestoreDBClusterToPointInTimeResultForRestoreDBClusterToPointInTime(
restoreDBClusterToPointInTimeResult: RestoreDBClusterToPointInTimeResult.__default)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromDBSnapshotMessage {
/**
Default instance of the RestoreDBInstanceFromDBSnapshotMessage structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromDBSnapshotMessage = {
let defaultInstance = RDSModel.RestoreDBInstanceFromDBSnapshotMessage(
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
copyTagsToSnapshot: nil,
dBInstanceClass: nil,
dBInstanceIdentifier: "value",
dBName: nil,
dBParameterGroupName: nil,
dBSnapshotIdentifier: "value",
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
engine: nil,
iops: nil,
licenseModel: nil,
multiAZ: nil,
optionGroupName: nil,
port: nil,
processorFeatures: nil,
publiclyAccessible: nil,
storageType: nil,
tags: nil,
tdeCredentialArn: nil,
tdeCredentialPassword: nil,
useDefaultProcessorFeatures: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromDBSnapshotResult {
/**
Default instance of the RestoreDBInstanceFromDBSnapshotResult structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromDBSnapshotResult = {
let defaultInstance = RDSModel.RestoreDBInstanceFromDBSnapshotResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromDBSnapshotResultForRestoreDBInstanceFromDBSnapshot {
/**
Default instance of the RestoreDBInstanceFromDBSnapshotResultForRestoreDBInstanceFromDBSnapshot structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromDBSnapshotResultForRestoreDBInstanceFromDBSnapshot = {
let defaultInstance = RDSModel.RestoreDBInstanceFromDBSnapshotResultForRestoreDBInstanceFromDBSnapshot(
restoreDBInstanceFromDBSnapshotResult: RestoreDBInstanceFromDBSnapshotResult.__default)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromS3Message {
/**
Default instance of the RestoreDBInstanceFromS3Message structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromS3Message = {
let defaultInstance = RDSModel.RestoreDBInstanceFromS3Message(
allocatedStorage: nil,
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
backupRetentionPeriod: nil,
copyTagsToSnapshot: nil,
dBInstanceClass: "value",
dBInstanceIdentifier: "value",
dBName: nil,
dBParameterGroupName: nil,
dBSecurityGroups: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
enablePerformanceInsights: nil,
engine: "value",
engineVersion: nil,
iops: nil,
kmsKeyId: nil,
licenseModel: nil,
masterUserPassword: nil,
masterUsername: nil,
maxAllocatedStorage: nil,
monitoringInterval: nil,
monitoringRoleArn: nil,
multiAZ: nil,
optionGroupName: nil,
performanceInsightsKMSKeyId: nil,
performanceInsightsRetentionPeriod: nil,
port: nil,
preferredBackupWindow: nil,
preferredMaintenanceWindow: nil,
processorFeatures: nil,
publiclyAccessible: nil,
s3BucketName: "value",
s3IngestionRoleArn: "value",
s3Prefix: nil,
sourceEngine: "value",
sourceEngineVersion: "value",
storageEncrypted: nil,
storageType: nil,
tags: nil,
useDefaultProcessorFeatures: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromS3Result {
/**
Default instance of the RestoreDBInstanceFromS3Result structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromS3Result = {
let defaultInstance = RDSModel.RestoreDBInstanceFromS3Result(
dBInstance: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceFromS3ResultForRestoreDBInstanceFromS3 {
/**
Default instance of the RestoreDBInstanceFromS3ResultForRestoreDBInstanceFromS3 structure.
*/
static let __default: RDSModel.RestoreDBInstanceFromS3ResultForRestoreDBInstanceFromS3 = {
let defaultInstance = RDSModel.RestoreDBInstanceFromS3ResultForRestoreDBInstanceFromS3(
restoreDBInstanceFromS3Result: RestoreDBInstanceFromS3Result.__default)
return defaultInstance
}()
}
public extension RestoreDBInstanceToPointInTimeMessage {
/**
Default instance of the RestoreDBInstanceToPointInTimeMessage structure.
*/
static let __default: RDSModel.RestoreDBInstanceToPointInTimeMessage = {
let defaultInstance = RDSModel.RestoreDBInstanceToPointInTimeMessage(
autoMinorVersionUpgrade: nil,
availabilityZone: nil,
copyTagsToSnapshot: nil,
dBInstanceClass: nil,
dBName: nil,
dBParameterGroupName: nil,
dBSubnetGroupName: nil,
deletionProtection: nil,
domain: nil,
domainIAMRoleName: nil,
enableCloudwatchLogsExports: nil,
enableIAMDatabaseAuthentication: nil,
engine: nil,
iops: nil,
licenseModel: nil,
maxAllocatedStorage: nil,
multiAZ: nil,
optionGroupName: nil,
port: nil,
processorFeatures: nil,
publiclyAccessible: nil,
restoreTime: nil,
sourceDBInstanceIdentifier: nil,
sourceDbiResourceId: nil,
storageType: nil,
tags: nil,
targetDBInstanceIdentifier: "value",
tdeCredentialArn: nil,
tdeCredentialPassword: nil,
useDefaultProcessorFeatures: nil,
useLatestRestorableTime: nil,
vpcSecurityGroupIds: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceToPointInTimeResult {
/**
Default instance of the RestoreDBInstanceToPointInTimeResult structure.
*/
static let __default: RDSModel.RestoreDBInstanceToPointInTimeResult = {
let defaultInstance = RDSModel.RestoreDBInstanceToPointInTimeResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension RestoreDBInstanceToPointInTimeResultForRestoreDBInstanceToPointInTime {
/**
Default instance of the RestoreDBInstanceToPointInTimeResultForRestoreDBInstanceToPointInTime structure.
*/
static let __default: RDSModel.RestoreDBInstanceToPointInTimeResultForRestoreDBInstanceToPointInTime = {
let defaultInstance = RDSModel.RestoreDBInstanceToPointInTimeResultForRestoreDBInstanceToPointInTime(
restoreDBInstanceToPointInTimeResult: RestoreDBInstanceToPointInTimeResult.__default)
return defaultInstance
}()
}
public extension RestoreWindow {
/**
Default instance of the RestoreWindow structure.
*/
static let __default: RDSModel.RestoreWindow = {
let defaultInstance = RDSModel.RestoreWindow(
earliestTime: nil,
latestTime: nil)
return defaultInstance
}()
}
public extension RevokeDBSecurityGroupIngressMessage {
/**
Default instance of the RevokeDBSecurityGroupIngressMessage structure.
*/
static let __default: RDSModel.RevokeDBSecurityGroupIngressMessage = {
let defaultInstance = RDSModel.RevokeDBSecurityGroupIngressMessage(
cIDRIP: nil,
dBSecurityGroupName: "value",
eC2SecurityGroupId: nil,
eC2SecurityGroupName: nil,
eC2SecurityGroupOwnerId: nil)
return defaultInstance
}()
}
public extension RevokeDBSecurityGroupIngressResult {
/**
Default instance of the RevokeDBSecurityGroupIngressResult structure.
*/
static let __default: RDSModel.RevokeDBSecurityGroupIngressResult = {
let defaultInstance = RDSModel.RevokeDBSecurityGroupIngressResult(
dBSecurityGroup: nil)
return defaultInstance
}()
}
public extension RevokeDBSecurityGroupIngressResultForRevokeDBSecurityGroupIngress {
/**
Default instance of the RevokeDBSecurityGroupIngressResultForRevokeDBSecurityGroupIngress structure.
*/
static let __default: RDSModel.RevokeDBSecurityGroupIngressResultForRevokeDBSecurityGroupIngress = {
let defaultInstance = RDSModel.RevokeDBSecurityGroupIngressResultForRevokeDBSecurityGroupIngress(
revokeDBSecurityGroupIngressResult: RevokeDBSecurityGroupIngressResult.__default)
return defaultInstance
}()
}
public extension SNSInvalidTopicFault {
/**
Default instance of the SNSInvalidTopicFault structure.
*/
static let __default: RDSModel.SNSInvalidTopicFault = {
let defaultInstance = RDSModel.SNSInvalidTopicFault()
return defaultInstance
}()
}
public extension SNSNoAuthorizationFault {
/**
Default instance of the SNSNoAuthorizationFault structure.
*/
static let __default: RDSModel.SNSNoAuthorizationFault = {
let defaultInstance = RDSModel.SNSNoAuthorizationFault()
return defaultInstance
}()
}
public extension SNSTopicArnNotFoundFault {
/**
Default instance of the SNSTopicArnNotFoundFault structure.
*/
static let __default: RDSModel.SNSTopicArnNotFoundFault = {
let defaultInstance = RDSModel.SNSTopicArnNotFoundFault()
return defaultInstance
}()
}
public extension ScalingConfiguration {
/**
Default instance of the ScalingConfiguration structure.
*/
static let __default: RDSModel.ScalingConfiguration = {
let defaultInstance = RDSModel.ScalingConfiguration(
autoPause: nil,
maxCapacity: nil,
minCapacity: nil,
secondsUntilAutoPause: nil,
timeoutAction: nil)
return defaultInstance
}()
}
public extension ScalingConfigurationInfo {
/**
Default instance of the ScalingConfigurationInfo structure.
*/
static let __default: RDSModel.ScalingConfigurationInfo = {
let defaultInstance = RDSModel.ScalingConfigurationInfo(
autoPause: nil,
maxCapacity: nil,
minCapacity: nil,
secondsUntilAutoPause: nil,
timeoutAction: nil)
return defaultInstance
}()
}
public extension SharedSnapshotQuotaExceededFault {
/**
Default instance of the SharedSnapshotQuotaExceededFault structure.
*/
static let __default: RDSModel.SharedSnapshotQuotaExceededFault = {
let defaultInstance = RDSModel.SharedSnapshotQuotaExceededFault()
return defaultInstance
}()
}
public extension SnapshotQuotaExceededFault {
/**
Default instance of the SnapshotQuotaExceededFault structure.
*/
static let __default: RDSModel.SnapshotQuotaExceededFault = {
let defaultInstance = RDSModel.SnapshotQuotaExceededFault()
return defaultInstance
}()
}
public extension SourceNotFoundFault {
/**
Default instance of the SourceNotFoundFault structure.
*/
static let __default: RDSModel.SourceNotFoundFault = {
let defaultInstance = RDSModel.SourceNotFoundFault()
return defaultInstance
}()
}
public extension SourceRegion {
/**
Default instance of the SourceRegion structure.
*/
static let __default: RDSModel.SourceRegion = {
let defaultInstance = RDSModel.SourceRegion(
endpoint: nil,
regionName: nil,
status: nil)
return defaultInstance
}()
}
public extension SourceRegionMessage {
/**
Default instance of the SourceRegionMessage structure.
*/
static let __default: RDSModel.SourceRegionMessage = {
let defaultInstance = RDSModel.SourceRegionMessage(
marker: nil,
sourceRegions: nil)
return defaultInstance
}()
}
public extension SourceRegionMessageForDescribeSourceRegions {
/**
Default instance of the SourceRegionMessageForDescribeSourceRegions structure.
*/
static let __default: RDSModel.SourceRegionMessageForDescribeSourceRegions = {
let defaultInstance = RDSModel.SourceRegionMessageForDescribeSourceRegions(
describeSourceRegionsResult: SourceRegionMessage.__default)
return defaultInstance
}()
}
public extension StartActivityStreamRequest {
/**
Default instance of the StartActivityStreamRequest structure.
*/
static let __default: RDSModel.StartActivityStreamRequest = {
let defaultInstance = RDSModel.StartActivityStreamRequest(
applyImmediately: nil,
kmsKeyId: "value",
mode: .__default,
resourceArn: "value")
return defaultInstance
}()
}
public extension StartActivityStreamResponse {
/**
Default instance of the StartActivityStreamResponse structure.
*/
static let __default: RDSModel.StartActivityStreamResponse = {
let defaultInstance = RDSModel.StartActivityStreamResponse(
applyImmediately: nil,
kinesisStreamName: nil,
kmsKeyId: nil,
mode: nil,
status: nil)
return defaultInstance
}()
}
public extension StartActivityStreamResponseForStartActivityStream {
/**
Default instance of the StartActivityStreamResponseForStartActivityStream structure.
*/
static let __default: RDSModel.StartActivityStreamResponseForStartActivityStream = {
let defaultInstance = RDSModel.StartActivityStreamResponseForStartActivityStream(
startActivityStreamResult: StartActivityStreamResponse.__default)
return defaultInstance
}()
}
public extension StartDBClusterMessage {
/**
Default instance of the StartDBClusterMessage structure.
*/
static let __default: RDSModel.StartDBClusterMessage = {
let defaultInstance = RDSModel.StartDBClusterMessage(
dBClusterIdentifier: "value")
return defaultInstance
}()
}
public extension StartDBClusterResult {
/**
Default instance of the StartDBClusterResult structure.
*/
static let __default: RDSModel.StartDBClusterResult = {
let defaultInstance = RDSModel.StartDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension StartDBClusterResultForStartDBCluster {
/**
Default instance of the StartDBClusterResultForStartDBCluster structure.
*/
static let __default: RDSModel.StartDBClusterResultForStartDBCluster = {
let defaultInstance = RDSModel.StartDBClusterResultForStartDBCluster(
startDBClusterResult: StartDBClusterResult.__default)
return defaultInstance
}()
}
public extension StartDBInstanceMessage {
/**
Default instance of the StartDBInstanceMessage structure.
*/
static let __default: RDSModel.StartDBInstanceMessage = {
let defaultInstance = RDSModel.StartDBInstanceMessage(
dBInstanceIdentifier: "value")
return defaultInstance
}()
}
public extension StartDBInstanceResult {
/**
Default instance of the StartDBInstanceResult structure.
*/
static let __default: RDSModel.StartDBInstanceResult = {
let defaultInstance = RDSModel.StartDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension StartDBInstanceResultForStartDBInstance {
/**
Default instance of the StartDBInstanceResultForStartDBInstance structure.
*/
static let __default: RDSModel.StartDBInstanceResultForStartDBInstance = {
let defaultInstance = RDSModel.StartDBInstanceResultForStartDBInstance(
startDBInstanceResult: StartDBInstanceResult.__default)
return defaultInstance
}()
}
public extension StartExportTaskMessage {
/**
Default instance of the StartExportTaskMessage structure.
*/
static let __default: RDSModel.StartExportTaskMessage = {
let defaultInstance = RDSModel.StartExportTaskMessage(
exportOnly: nil,
exportTaskIdentifier: "value",
iamRoleArn: "value",
kmsKeyId: "value",
s3BucketName: "value",
s3Prefix: nil,
sourceArn: "value")
return defaultInstance
}()
}
public extension StopActivityStreamRequest {
/**
Default instance of the StopActivityStreamRequest structure.
*/
static let __default: RDSModel.StopActivityStreamRequest = {
let defaultInstance = RDSModel.StopActivityStreamRequest(
applyImmediately: nil,
resourceArn: "value")
return defaultInstance
}()
}
public extension StopActivityStreamResponse {
/**
Default instance of the StopActivityStreamResponse structure.
*/
static let __default: RDSModel.StopActivityStreamResponse = {
let defaultInstance = RDSModel.StopActivityStreamResponse(
kinesisStreamName: nil,
kmsKeyId: nil,
status: nil)
return defaultInstance
}()
}
public extension StopActivityStreamResponseForStopActivityStream {
/**
Default instance of the StopActivityStreamResponseForStopActivityStream structure.
*/
static let __default: RDSModel.StopActivityStreamResponseForStopActivityStream = {
let defaultInstance = RDSModel.StopActivityStreamResponseForStopActivityStream(
stopActivityStreamResult: StopActivityStreamResponse.__default)
return defaultInstance
}()
}
public extension StopDBClusterMessage {
/**
Default instance of the StopDBClusterMessage structure.
*/
static let __default: RDSModel.StopDBClusterMessage = {
let defaultInstance = RDSModel.StopDBClusterMessage(
dBClusterIdentifier: "value")
return defaultInstance
}()
}
public extension StopDBClusterResult {
/**
Default instance of the StopDBClusterResult structure.
*/
static let __default: RDSModel.StopDBClusterResult = {
let defaultInstance = RDSModel.StopDBClusterResult(
dBCluster: nil)
return defaultInstance
}()
}
public extension StopDBClusterResultForStopDBCluster {
/**
Default instance of the StopDBClusterResultForStopDBCluster structure.
*/
static let __default: RDSModel.StopDBClusterResultForStopDBCluster = {
let defaultInstance = RDSModel.StopDBClusterResultForStopDBCluster(
stopDBClusterResult: StopDBClusterResult.__default)
return defaultInstance
}()
}
public extension StopDBInstanceMessage {
/**
Default instance of the StopDBInstanceMessage structure.
*/
static let __default: RDSModel.StopDBInstanceMessage = {
let defaultInstance = RDSModel.StopDBInstanceMessage(
dBInstanceIdentifier: "value",
dBSnapshotIdentifier: nil)
return defaultInstance
}()
}
public extension StopDBInstanceResult {
/**
Default instance of the StopDBInstanceResult structure.
*/
static let __default: RDSModel.StopDBInstanceResult = {
let defaultInstance = RDSModel.StopDBInstanceResult(
dBInstance: nil)
return defaultInstance
}()
}
public extension StopDBInstanceResultForStopDBInstance {
/**
Default instance of the StopDBInstanceResultForStopDBInstance structure.
*/
static let __default: RDSModel.StopDBInstanceResultForStopDBInstance = {
let defaultInstance = RDSModel.StopDBInstanceResultForStopDBInstance(
stopDBInstanceResult: StopDBInstanceResult.__default)
return defaultInstance
}()
}
public extension StorageQuotaExceededFault {
/**
Default instance of the StorageQuotaExceededFault structure.
*/
static let __default: RDSModel.StorageQuotaExceededFault = {
let defaultInstance = RDSModel.StorageQuotaExceededFault()
return defaultInstance
}()
}
public extension StorageTypeNotSupportedFault {
/**
Default instance of the StorageTypeNotSupportedFault structure.
*/
static let __default: RDSModel.StorageTypeNotSupportedFault = {
let defaultInstance = RDSModel.StorageTypeNotSupportedFault()
return defaultInstance
}()
}
public extension Subnet {
/**
Default instance of the Subnet structure.
*/
static let __default: RDSModel.Subnet = {
let defaultInstance = RDSModel.Subnet(
subnetAvailabilityZone: nil,
subnetIdentifier: nil,
subnetOutpost: nil,
subnetStatus: nil)
return defaultInstance
}()
}
public extension SubnetAlreadyInUse {
/**
Default instance of the SubnetAlreadyInUse structure.
*/
static let __default: RDSModel.SubnetAlreadyInUse = {
let defaultInstance = RDSModel.SubnetAlreadyInUse()
return defaultInstance
}()
}
public extension SubscriptionAlreadyExistFault {
/**
Default instance of the SubscriptionAlreadyExistFault structure.
*/
static let __default: RDSModel.SubscriptionAlreadyExistFault = {
let defaultInstance = RDSModel.SubscriptionAlreadyExistFault()
return defaultInstance
}()
}
public extension SubscriptionCategoryNotFoundFault {
/**
Default instance of the SubscriptionCategoryNotFoundFault structure.
*/
static let __default: RDSModel.SubscriptionCategoryNotFoundFault = {
let defaultInstance = RDSModel.SubscriptionCategoryNotFoundFault()
return defaultInstance
}()
}
public extension SubscriptionNotFoundFault {
/**
Default instance of the SubscriptionNotFoundFault structure.
*/
static let __default: RDSModel.SubscriptionNotFoundFault = {
let defaultInstance = RDSModel.SubscriptionNotFoundFault()
return defaultInstance
}()
}
public extension Tag {
/**
Default instance of the Tag structure.
*/
static let __default: RDSModel.Tag = {
let defaultInstance = RDSModel.Tag(
key: nil,
value: nil)
return defaultInstance
}()
}
public extension TagListMessage {
/**
Default instance of the TagListMessage structure.
*/
static let __default: RDSModel.TagListMessage = {
let defaultInstance = RDSModel.TagListMessage(
tagList: nil)
return defaultInstance
}()
}
public extension TagListMessageForListTagsForResource {
/**
Default instance of the TagListMessageForListTagsForResource structure.
*/
static let __default: RDSModel.TagListMessageForListTagsForResource = {
let defaultInstance = RDSModel.TagListMessageForListTagsForResource(
listTagsForResourceResult: TagListMessage.__default)
return defaultInstance
}()
}
public extension TargetHealth {
/**
Default instance of the TargetHealth structure.
*/
static let __default: RDSModel.TargetHealth = {
let defaultInstance = RDSModel.TargetHealth(
description: nil,
reason: nil,
state: nil)
return defaultInstance
}()
}
public extension Timezone {
/**
Default instance of the Timezone structure.
*/
static let __default: RDSModel.Timezone = {
let defaultInstance = RDSModel.Timezone(
timezoneName: nil)
return defaultInstance
}()
}
public extension UpgradeTarget {
/**
Default instance of the UpgradeTarget structure.
*/
static let __default: RDSModel.UpgradeTarget = {
let defaultInstance = RDSModel.UpgradeTarget(
autoUpgrade: nil,
description: nil,
engine: nil,
engineVersion: nil,
isMajorVersionUpgrade: nil)
return defaultInstance
}()
}
public extension UserAuthConfig {
/**
Default instance of the UserAuthConfig structure.
*/
static let __default: RDSModel.UserAuthConfig = {
let defaultInstance = RDSModel.UserAuthConfig(
authScheme: nil,
description: nil,
iAMAuth: nil,
secretArn: nil,
userName: nil)
return defaultInstance
}()
}
public extension UserAuthConfigInfo {
/**
Default instance of the UserAuthConfigInfo structure.
*/
static let __default: RDSModel.UserAuthConfigInfo = {
let defaultInstance = RDSModel.UserAuthConfigInfo(
authScheme: nil,
description: nil,
iAMAuth: nil,
secretArn: nil,
userName: nil)
return defaultInstance
}()
}
public extension ValidDBInstanceModificationsMessage {
/**
Default instance of the ValidDBInstanceModificationsMessage structure.
*/
static let __default: RDSModel.ValidDBInstanceModificationsMessage = {
let defaultInstance = RDSModel.ValidDBInstanceModificationsMessage(
storage: nil,
validProcessorFeatures: nil)
return defaultInstance
}()
}
public extension ValidStorageOptions {
/**
Default instance of the ValidStorageOptions structure.
*/
static let __default: RDSModel.ValidStorageOptions = {
let defaultInstance = RDSModel.ValidStorageOptions(
iopsToStorageRatio: nil,
provisionedIops: nil,
storageSize: nil,
storageType: nil,
supportsStorageAutoscaling: nil)
return defaultInstance
}()
}
public extension VpcSecurityGroupMembership {
/**
Default instance of the VpcSecurityGroupMembership structure.
*/
static let __default: RDSModel.VpcSecurityGroupMembership = {
let defaultInstance = RDSModel.VpcSecurityGroupMembership(
status: nil,
vpcSecurityGroupId: nil)
return defaultInstance
}()
}
public extension VpnDetails {
/**
Default instance of the VpnDetails structure.
*/
static let __default: RDSModel.VpnDetails = {
let defaultInstance = RDSModel.VpnDetails(
vpnGatewayIp: nil,
vpnId: nil,
vpnName: nil,
vpnPSK: nil,
vpnState: nil,
vpnTunnelOriginatorIP: nil)
return defaultInstance
}()
}
| 31.592164 | 125 | 0.698501 |
46ffc401281c85758b0c4fd0ea93e8566b2ff5d9 | 2,387 | //
// SettingsView.swift
// LoginForm
//
// Created by Lukas on 28.03.21.
// Copyright © 2021 Lukas. All rights reserved.
//
import SwiftUI
struct SettingsView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
if #available(iOS 14.0, *) {
NavigationView {
List {
Section {
Button(action: {},
label: {
SettingsCell(title: "Features", imgName: "sparkle", clr: .purple)
.foregroundColor(colorScheme == .dark ? .white : .black)
})
Button(action: {},
label: {
SettingsCell(title: "Settings", imgName: "sparkle", clr: .purple)
.foregroundColor(colorScheme == .dark ? .white : .black)
})
Button(action: {},
label: {
SettingsCell(title: "Bla", imgName: "sparkle", clr: .purple)
.foregroundColor(colorScheme == .dark ? .white : .black)
})
}
Section {
Button(action: {},
label: {
SettingsCell(title: "Features", imgName: "sparkle", clr: .purple)
.foregroundColor(colorScheme == .dark ? .white : .black)
})
Button(action: {},
label: {
SettingsCell(title: "Settings", imgName: "sparkle", clr: .purple)
.foregroundColor(colorScheme == .dark ? .white : .black)
})
}
}
}
.listStyle(GroupedListStyle())
// .environment(\.horizontalSizeClass, .regular)
.navigationTitle("Settings")
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
| 37.296875 | 97 | 0.37788 |
6767ba35042bf8ddaccacdfc2154d6ccdedd2ad5 | 4,465 | //
// EncodingManager.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-09-24.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2020 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Cocoa
@objc protocol EncodingHolder: AnyObject {
func changeEncoding(_ sender: NSMenuItem)
}
// MARK: -
final class EncodingManager {
// MARK: Public Properties
static let shared = EncodingManager()
@Published private(set) var encodings: [String.Encoding?] = []
// MARK: Private Properties
private var encodingListObserver: AnyCancellable?
// MARK: -
// MARK: Lifecycle
private init() {
// -> UserDefaults.standard[.encodingList] can be empty if the user's list contains negative values.
// It seems to be possible if the setting was made a long time ago. (2018-01 CotEditor 3.3.0)
if UserDefaults.standard[.encodingList].isEmpty {
self.sanitizeEncodingListSetting()
}
self.encodingListObserver = UserDefaults.standard.publisher(for: .encodingList, initial: true)
.map { $0.map { $0 != kCFStringEncodingInvalidId ? String.Encoding(cfEncoding: $0) : nil } }
.sink { [weak self] in self?.encodings = $0 }
}
// MARK: Public Methods
/// returns corresponding NSStringEncoding from a encoding name
func encoding(name encodingName: String) -> String.Encoding? {
return DefaultSettings.encodings.lazy
.filter { $0 != kCFStringEncodingInvalidId } // = separator
.map { String.Encoding(cfEncoding: $0) }
.first { encodingName == String.localizedName(of: $0) }
}
/// return copied encoding menu items
func createEncodingMenuItems() -> [NSMenuItem] {
return self.encodings.map { encoding in
guard let encoding = encoding else {
return .separator()
}
let item = NSMenuItem()
item.title = String.localizedName(of: encoding)
item.tag = Int(encoding.rawValue)
return item
}
}
/// set available encoding menu items with action to passed-in menu
func updateChangeEncodingMenu(_ menu: NSMenu) {
menu.items.removeAll { $0.action == #selector(EncodingHolder.changeEncoding) }
for item in self.createEncodingMenuItems() {
item.action = #selector(EncodingHolder.changeEncoding)
item.target = nil
menu.addItem(item)
// add "UTF-8 with BOM" item just after the normal UTF-8
if item.tag == FileEncoding(encoding: .utf8).tag {
let fileEncoding = FileEncoding(encoding: .utf8, withUTF8BOM: true)
let bomItem = NSMenuItem(title: fileEncoding.localizedName,
action: #selector(EncodingHolder.changeEncoding),
keyEquivalent: "")
bomItem.tag = fileEncoding.tag
menu.addItem(bomItem)
}
}
}
// MARK: Private Methods
/// convert invalid encoding values (-1) to `kCFStringEncodingInvalidId`
private func sanitizeEncodingListSetting() {
guard
let list = UserDefaults.standard.array(forKey: DefaultKeys.encodingList.rawValue) as? [Int],
!list.isEmpty else {
// just restore to default if failed
UserDefaults.standard.restore(key: .encodingList)
return
}
UserDefaults.standard[.encodingList] = list.map { CFStringEncoding(exactly: $0) ?? kCFStringEncodingInvalidId }
}
}
| 31.666667 | 119 | 0.587234 |
ef605e968e82cedfa2cf4e0132fe4324169dfe4a | 5,904 | //
// LectureListCell.swift
// HTWDD
//
// Created by Fabian Ehlert on 01.11.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
class LectureListCell: FlatCollectionViewCell, Cell {
enum Const {
static let textColor = UIColor.black
static let margin: CGFloat = 8
}
// MARK: - UI
let beginLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 16, weight: .medium)
label.textColor = UIColor.htw.textHeadline
label.textAlignment = .right
return label
}()
let endLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 16, weight: .medium)
label.textColor = UIColor.htw.textHeadline
label.textAlignment = .right
return label
}()
let colorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.htw.orange
view.layer.cornerRadius = 2
return view
}()
let titleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 18, weight: .medium)
label.textColor = UIColor.htw.textHeadline
label.textAlignment = .left
label.numberOfLines = 2
label.lineBreakMode = .byWordWrapping
return label
}()
let professorLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 15, weight: .medium)
label.textColor = UIColor.htw.mediumGrey
label.textAlignment = .left
return label
}()
let typeLabel: BadgeLabel = {
let label = BadgeLabel()
label.backgroundColor = UIColor(hex: 0xE8E8E8)
label.font = .systemFont(ofSize: 13, weight: .semibold)
label.textColor = UIColor.htw.textHeadline
return label
}()
let roomLabel: BadgeLabel = {
let label = BadgeLabel()
label.backgroundColor = UIColor(hex: 0xCFCFCF)
label.font = .systemFont(ofSize: 13, weight: .semibold)
label.textColor = UIColor.htw.textHeadline
return label
}()
// MARK: - Init
override func initialSetup() {
super.initialSetup()
self.contentView.add(self.beginLabel,
self.endLabel,
self.colorView,
self.titleLabel,
self.professorLabel,
self.typeLabel,
self.roomLabel)
}
func updateLayout(width: CGFloat) {
let innerMargin: CGFloat = 2
let timeWidth: CGFloat = 48
self.beginLabel.frame = CGRect(origin: CGPoint(x: Const.margin, y: Const.margin),
size: CGSize(width: timeWidth, height: 21))
self.endLabel.frame = CGRect(origin: CGPoint(x: Const.margin, y: self.height - 21 - Const.margin),
size: CGSize(width: timeWidth, height: 21))
self.colorView.frame = CGRect(x: self.beginLabel.right + Const.margin, y: Const.margin,
width: 4, height: self.contentView.height - Const.margin*2)
let labelsStart = Const.margin * 3 + self.beginLabel.width + self.colorView.width
let labelsWidth = width - labelsStart - Const.margin
func sizeForLabel(label: UILabel) -> CGSize {
let height = label.sizeThatFits(CGSize(width: labelsWidth, height: CGFloat.greatestFiniteMagnitude)).height
return CGSize(width: labelsWidth, height: height)
}
self.titleLabel.frame = CGRect(origin: CGPoint(x: labelsStart, y: Const.margin),
size: sizeForLabel(label: self.titleLabel))
self.professorLabel.frame = CGRect(origin: CGPoint(x: labelsStart, y: self.titleLabel.bottom + innerMargin),
size: sizeForLabel(label: self.professorLabel))
self.updateBadges(innerMargin: innerMargin, labelsStart: labelsStart)
self.colorView.frame = CGRect(x: self.beginLabel.right + Const.margin, y: Const.margin,
width: 4, height: (self.typeLabel.bottom - self.titleLabel.top) + 3)
}
override func layoutSubviews() {
super.layoutSubviews()
self.updateLayout(width: self.contentView.width)
}
func update(viewModel: LectureViewModel) {
self.colorView.backgroundColor = UIColor(hex: viewModel.color)
self.beginLabel.text = viewModel.begin
self.endLabel.text = viewModel.end
self.titleLabel.text = viewModel.longTitle
self.professorLabel.text = viewModel.professor
self.typeLabel.text = viewModel.type
self.roomLabel.text = viewModel.room
self.roomLabel.alpha = viewModel.room != nil ? 1 : 0
let innerMargin: CGFloat = 2
let labelsStart = Const.margin * 3 + self.beginLabel.width + self.colorView.width
self.updateBadges(innerMargin: innerMargin, labelsStart: labelsStart)
}
private func updateBadges(innerMargin: CGFloat, labelsStart: CGFloat) {
self.typeLabel.frame = CGRect(origin: CGPoint(x: labelsStart, y: self.professorLabel.bottom + (innerMargin*3)),
size: CGSize(width: self.typeLabel.intrinsicContentSize.width, height: 19))
let roomWidth = min(self.contentView.width - labelsStart - Const.margin - self.typeLabel.width - (innerMargin*3), self.roomLabel.intrinsicContentSize.width)
self.roomLabel.frame = CGRect(origin: CGPoint(x: self.typeLabel.right + (innerMargin*3), y: self.professorLabel.bottom + (innerMargin*3)),
size: CGSize(width: roomWidth, height: 19))
}
}
extension LectureListCell: HeightCalculator {
static func height(for width: CGFloat, viewModel: LectureViewModel) -> CGFloat {
let cell = LectureListCell()
cell.update(viewModel: viewModel)
cell.updateLayout(width: width)
return cell.colorView.height + Const.margin*2
}
}
| 35.781818 | 158 | 0.629912 |
d534b746deee6203a944e159523ada5a3bc5bc2d | 3,364 | //
// Renderer.swift
// LiveCode-macOS
//
// Created by Reza Ali on 6/1/20.
// Copyright © 2020 Hi-Rez. All rights reserved.
//
// This example shows how to generate custom geometry using C
import Metal
import MetalKit
import Forge
import Satin
open class IcosahedronGeometry: Geometry {
public init(size: Float = 2, res: Int = 6) {
super.init()
setupData(size: size, res: res)
}
func setupData(size: Float, res: Int) {
primitiveType = .triangle
var geo = generateIcosahedronGeometryData(size, Int32(res))
let vCount = Int(geo.vertexCount)
if vCount > 0, let data = geo.vertexData {
vertexData = Array(UnsafeBufferPointer(start: data, count: vCount))
}
let indexCount = Int(geo.indexCount)*3
if indexCount > 0, let data = geo.indexData {
data.withMemoryRebound(to: UInt32.self, capacity: indexCount) { ptr in
indexData = Array(UnsafeBufferPointer(start: ptr, count: indexCount))
}
}
freeGeometryData(&geo)
}
}
class Renderer: Forge.Renderer {
var assetsURL: URL {
let resourcesURL = Bundle.main.resourceURL!
return resourcesURL.appendingPathComponent("Assets")
}
var texturesURL: URL {
return assetsURL.appendingPathComponent("Textures")
}
var modelsURL: URL {
return assetsURL.appendingPathComponent("Models")
}
var scene = Object()
lazy var context: Context = {
Context(device, sampleCount, colorPixelFormat, depthPixelFormat, stencilPixelFormat)
}()
lazy var camera: PerspectiveCamera = {
let camera = PerspectiveCamera()
camera.position = simd_make_float3(0.0, 0.0, 6.0)
camera.near = 0.001
camera.far = 100.0
return camera
}()
lazy var cameraController: PerspectiveCameraController = {
PerspectiveCameraController(camera: camera, view: mtkView)
}()
lazy var renderer: Satin.Renderer = {
let renderer = Satin.Renderer(context: context, scene: scene, camera: camera)
renderer.clearColor = .init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
return renderer
}()
var mesh: Mesh!
override func setupMtkView(_ metalKitView: MTKView) {
metalKitView.sampleCount = 1
metalKitView.depthStencilPixelFormat = .depth32Float
metalKitView.preferredFramesPerSecond = 60
metalKitView.colorPixelFormat = .bgra8Unorm
}
override func setup() {
setupMesh()
}
func setupMesh() {
mesh = Mesh(geometry: IcosahedronGeometry(size: 1.0, res: 4), material: NormalColorMaterial(true))
mesh.label = "Icosahedron"
mesh.triangleFillMode = .lines
scene.add(mesh)
}
override func update() {
cameraController.update()
}
override func draw(_ view: MTKView, _ commandBuffer: MTLCommandBuffer) {
guard let renderPassDescriptor = view.currentRenderPassDescriptor else { return }
renderer.draw(renderPassDescriptor: renderPassDescriptor, commandBuffer: commandBuffer)
}
override func resize(_ size: (width: Float, height: Float)) {
let aspect = size.width / size.height
camera.aspect = aspect
renderer.resize(size)
}
}
| 29.508772 | 106 | 0.634067 |
8a10e29e5e2aafe70b800704cff657800815e672 | 1,450 | //: A UIKit based Playground for presenting user interface
import UIKit
import AVKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let videoURL = "https://vsd4.mycdn.me/hls/608030952065.m3u8/sig/-D34YezIYz4/expires/1587851966019/srcIp/176.175.59.169/clientType/0/srcAg/GECKO/mid/1425481014913/608030952065_high/index.m3u8"
let headers: [String:String] = ["User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36"]
let asset = AVURLAsset(url: URL(string: videoURL)!, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
player.play()
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
view.addSubview(label)
self.view = view
let playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true) {
player.play()
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
| 37.179487 | 199 | 0.662759 |
c185dc287657371ab4cf007971e92a1ebd88c659 | 1,094 |
import XCTest
class TumblrUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 35.290323 | 182 | 0.659049 |
23a9577f3ae6101019316737978621e2fd4a66ab | 4,569 | //
// NetworkManager.swift
// NewsApp
//
// Created by Macbook Pro 15 on 4/24/20.
// Copyright © 2020 SamuelFolledo. All rights reserved.
//
import UIKit
class NetworkManager {
static let shared = NetworkManager()
private init() {}
//MARK: -
// shared singleton session object used to run tasks. Will be useful later
private let urlSession = URLSession.shared
private let apiKey = "f7971dc8dd764567b33544a9daf7fcae"
//TODO: move to VC or even ViewModel, first refactor to MVVM
var numArticlesOnBackend = 0
//MARK: - fetch
//??
/// Use Endpoint.category for category VC with sources, and Endpoint.articles for list of articles with parameters
func fetchArticles(_ endpoint: EndPoint,
pageParams: [URLQueryItem]? = nil,
completion: @escaping (Result<[Article]>) -> ()) {
let pageParams1: [URLQueryItem]
if let params = pageParams {
pageParams1 = params
} else {
pageParams1 = NetworkManager.makeURLQueryItems()
}
let request = endpoint.makeURLRequest(with: apiKey, pageParams: pageParams1)
print("Sending request to: \(request.url!)")
let task = urlSession.dataTask(with: request) { data, _, error in
if let error = error {
return completion(.failure(error))
}
guard let data = data else {
return completion(.failure(EndPointError.noData(message: "Articles has no data")))
}
guard let result = try? JSONDecoder().decode(ArticleList.self, from: data) else {
//FIXME: wrong error, can be no sources, not parsing error
return completion(.failure(EndPointError.couldNotParse(message: "Could not parse Articles")))
}
guard let status = result.status else {
return completion(.failure(EndPointError.couldNotParse(message: result.message ?? EndPointError.unknown())))
}
guard status != "error" else {
guard let errorMessage = result.message,
let errorCode = result.code else {
return completion(.failure(EndPointError.unknown()))
}
switch errorCode {
case "maximumResultsReached":
return completion(.failure(EndPointError.maximumResultsReached()))
default:
return completion(.failure(EndPointError.endpointError(message: "Endpoint Error \(errorCode): \(errorMessage)")))
}
return
}
self.numArticlesOnBackend = result.totalResults!
completion(.success(result.articles!))
}
task.resume()
}
//TODO:
// add filter options - category, country, language
// see https://newsapi.org/docs/endpoints/sources
func fetchAllSources(completion: @escaping (Result<[Source]>) -> ()) {
let request = EndPoint.sources.makeURLRequest(with: apiKey)
print("Sending request to: \(request.url!)")
let task = urlSession.dataTask(with: request) { data, _, error in
if let error = error {
return completion(.failure(error))
}
guard let data = data else {
return completion(.failure(EndPointError.noData(message: "Sources has no data")))
}
//FIXME: wrong error, can be no sources, not parsing error
guard let result = try? JSONDecoder().decode(Sources.self, from: data) else {
return completion(.failure(EndPointError.couldNotParse(message: "Could not parse sources")))
}
if result.status != "ok" {
completion(.failure(EndPointError.endpointError(message: result.message ?? "Unknown endpoint error")))
} else {
let sources = result.sources
completion(.success(sources))
}
}
task.resume()
}
static func makeURLQueryItems(page: Int = 1,
pageSize: Int = 20) -> [URLQueryItem] {
[
URLQueryItem(name: "page",
value: String(page)),
URLQueryItem(name: "pageSize",
value: String(pageSize))
]
}
}
enum Result<T> {
case success(T)
case failure(Error)
}
| 36.552 | 133 | 0.560954 |
6a2a30a4cb0e2126df459a6e164597f04003d052 | 1,350 | //
// Types.swift
// SavannaKit
//
// Created by Louis D'hauwe on 24/06/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
public typealias View = NSView
public typealias ViewController = NSViewController
public typealias Window = NSWindow
public typealias Control = NSControl
public typealias TextView = NSTextView
public typealias TextField = NSTextField
public typealias Button = NSButton
public typealias Font = NSFont
public typealias Color = NSColor
public typealias StackView = NSStackView
public typealias Image = NSImage
public typealias BezierPath = NSBezierPath
public typealias ScrollView = NSScrollView
public typealias Screen = NSScreen
#else
import UIKit
public typealias View = UIView
public typealias ViewController = UIViewController
public typealias Window = UIWindow
public typealias Control = UIControl
public typealias TextView = UITextView
public typealias TextField = UITextField
public typealias Button = UIButton
public typealias Font = UIFont
public typealias Color = UIColor
public typealias StackView = UIStackView
public typealias Image = UIImage
public typealias BezierPath = UIBezierPath
public typealias ScrollView = UIScrollView
public typealias Screen = UIScreen
#endif
| 26.470588 | 53 | 0.765926 |
916adf2e575b35fddca2b3354c34d5f431c7c872 | 280 | //
// StringAtom.swift
// macbert
//
// Created by Anton Makarov on 19.07.2017.
// Copyright © 2017 TecSynt Solutions. All rights reserved.
//
import Foundation
class StringAtom {
var string: String? = nil
init(string: String) {
self.string = string
}
}
| 16.470588 | 60 | 0.642857 |
f864c8be9ad92b7c8f6af7416a85331c31987c55 | 3,190 | //
// Created by Mac Book on 6/7/20.
//
import Foundation
protocol CBAPIResource {
associatedtype ModelType: Decodable
associatedtype ErrorType: Decodable
var methodPath: String { get }
var baseUrl: String { get }
var authHeader: String? { get }
var header: [String: String]? { get }
var url: URLRequest { get }
var requestBody: URLEncodedRequestBody? { get }
func create() -> URLRequest
var queryParams: [String: String]? { get set}
}
extension CBAPIResource {
var authHeader: String? {
get {
nil
}
}
var header: [String: String]? {
get {
nil
}
}
var queryParams: [String: String]? {
get { return nil } set {}
}
var requestBody: URLEncodedRequestBody? {
get {
nil
}
}
var url: URLRequest {
buildBaseRequest()
}
func create() -> URLRequest {
var urlRequest = buildBaseRequest()
urlRequest.httpMethod = "post"
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var bodyComponents = URLComponents()
bodyComponents.queryItems = requestBody?.toFormBody().map({ (key, value) -> URLQueryItem in
URLQueryItem(name: key, value: value)
})
urlRequest.httpBody = bodyComponents.query?.data(using: .utf8)
// print(bodyComponents.query?.data(using: .utf8))
return urlRequest
}
private func buildBaseRequest() -> URLRequest {
// TODO: Remove force unwrapping
var components = URLComponents(string: baseUrl)
components!.path += methodPath
if let queryParams = queryParams {
components?.queryItems = queryItems(dictionary: queryParams)
}
var urlRequest = URLRequest(url: components!.url!)
if let authHeader = authHeader {
urlRequest.addValue(authHeader, forHTTPHeaderField: "Authorization")
}
header?.forEach({ (key, value) in
urlRequest.addValue(value, forHTTPHeaderField: key)
})
return urlRequest
}
}
class CBAPIRequest<Resource: CBAPIResource> {
let resource: Resource
init(resource: Resource) {
self.resource = resource
}
}
extension CBAPIRequest: CBNetworkRequest {
func decode(_ data: Data) -> Resource.ModelType? {
return try? JSONDecoder().decode(Resource.ModelType.self, from: data)
}
func decodeError(_ data: Data) -> Resource.ErrorType? {
return try? JSONDecoder().decode(Resource.ErrorType.self, from: data)
}
func load(withCompletion completion: SuccessHandler<Resource.ModelType>? = nil, onError: ErrorHandler? = nil) {
load(resource.url, withCompletion: completion, onError: onError)
}
func create(withCompletion completion: SuccessHandler<Resource.ModelType>? = nil, onError: ErrorHandler? = nil) {
load(resource.create(), withCompletion: completion, onError: onError)
}
}
func queryItems(dictionary: [String: String]) -> [URLQueryItem] {
return dictionary.map {
// Swift 4
URLQueryItem(name: $0.0, value: $0.1)
}
}
| 27.982456 | 117 | 0.6279 |
62a58f795bad77b41edd9a802d61a528962c92b1 | 206 | //
// ResponseCode.swift
// Storizy-iOS
//
// Created by 임수정 on 2021/11/12.
//
import Foundation
enum ResponseCode {
case success
case requestError
case serverError
case networkError
}
| 12.875 | 33 | 0.674757 |
7215236dbc606c5bee0fdfb5cab7fba5123039e8 | 2,566 | //
// IncompatibleCharacterScanner.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-05-28.
//
// ---------------------------------------------------------------------------
//
// © 2016-2018 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AppKit
protocol IncompatibleCharacterScannerDelegate: class {
func needsUpdateIncompatibleCharacter(_ document: Document) -> Bool
func document(_ document: Document, didUpdateIncompatibleCharacters incompatibleCharacters: [IncompatibleCharacter])
}
final class IncompatibleCharacterScanner: CustomDebugStringConvertible {
// MARK: Public Properties
weak var delegate: IncompatibleCharacterScannerDelegate?
private(set) weak var document: Document? // weak to avoid cycle retain
private(set) var incompatibleCharacters = [IncompatibleCharacter]() // line endings applied
// MARK: Private Properties
private lazy var updateTask = Debouncer(delay: .milliseconds(400)) { [weak self] in self?.scan() }
// MARK: -
// MARK: Lifecycle
required init(document: Document) {
self.document = document
}
var debugDescription: String {
return "<\(self): \(self.document?.displayName ?? "NO DOCUMENT")>"
}
// MARK: Public Methods
/// set update timer
func invalidate() {
guard
let document = self.document,
self.delegate?.needsUpdateIncompatibleCharacter(document) ?? false else { return }
self.updateTask.schedule()
}
/// scan immediately
func scan() {
guard let document = self.document else { return }
self.incompatibleCharacters = document.string.scanIncompatibleCharacters(for: document.encoding)
self.updateTask.cancel()
self.delegate?.document(document, didUpdateIncompatibleCharacters: self.incompatibleCharacters)
}
}
| 27.297872 | 120 | 0.639127 |
18315dea43878eb5bd4e0a831d8144be9e99388d | 4,603 | //
// StringExtension.swift
// Sequel Ace
//
// Created by Jakub Kaspar on 22.07.2020.
// Copyright © 2020 Sequel-Ace. All rights reserved.
//
import Foundation
import os.log
extension String {
func dropPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else {
return self
}
return String(self.dropFirst(prefix.count))
}
func dropSuffix(_ suffix: String) -> String {
guard self.hasSuffix(suffix) else {
return self
}
return String(self.dropLast(suffix.count))
}
func hasPrefix(_ prefix: String, caseSensitive: Bool = true) -> Bool {
switch caseSensitive {
case true:
return self.hasPrefix(prefix)
case false:
return self.lowercased().hasPrefix(prefix.lowercased())
}
}
func hasSuffix(_ suffix: String, caseSensitive: Bool = true) -> Bool {
switch caseSensitive {
case true:
return self.hasSuffix(suffix)
case false:
return self.lowercased().hasSuffix(suffix.lowercased())
}
}
func separatedIntoLines() -> [String] {
var lines: [String] = []
let wholeString = self.startIndex..<self.endIndex
self.enumerateSubstrings(in: wholeString, options: .byLines) {
(substring, range, enclosingRange, stopPointer) in
if let line = substring {
lines.append(line)
}
}
return lines
}
var isNumeric: Bool {
return !(self.isEmpty) && self.allSatisfy { $0.isNumber }
}
// stringByReplacingPercentEscapesUsingEncoding is deprecated
// Use -stringByRemovingPercentEncoding
// however: per https://developer.apple.com/documentation/foundation/nsstring/1409569-stringbyremovingpercentencoding?language=objc
// You must call this method only on strings that you know to be percent-encoded
// Generally, removingPercentEncoding fails when the original String contains non-escaped percent symbols
// so before we replace stringByReplacingPercentEscapesUsingEncoding all over
// we should check the string first
var isPercentEncoded: Bool {
guard let decoded = self.removingPercentEncoding else {
return false
}
return self != decoded
}
// the string with new lines and spaces trimmed from BOTH ends
var trimmedString: String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
@objc extension NSString {
public func dropPrefix(prefix: NSString) -> NSString {
return (self as String).dropPrefix(prefix as String) as NSString
}
public func dropSuffix(suffix: NSString) -> NSString {
return (self as String).dropSuffix(suffix as String) as NSString
}
public func hasPrefix(prefix: NSString, caseSensitive: Bool = true) -> Bool {
return (self as String).hasPrefix(prefix as String, caseSensitive: caseSensitive)
}
public func hasSuffix(suffix: NSString, caseSensitive: Bool = true) -> Bool {
return (self as String).hasSuffix(suffix as String, caseSensitive: caseSensitive)
}
public func trimWhitespacesAndNewlines() -> NSString {
return (self as String).trimmedString as NSString
}
public func isPercentEncoded() -> Bool {
return (self as String).isPercentEncoded
}
public func separatedIntoLinesObjc() -> [NSString] {
return (self as String).separatedIntoLines() as [NSString]
}
public func dateStringFromUnixTimestamp() -> NSString? {
os_log("string [%@]", log: OSLog.default, type: .error, self)
guard
!(self as String).isEmpty,
(self as String).dropPrefix("-").isNumeric,
let timeInterval = self.doubleValue as Double?,
timeInterval != 0.0
else{
os_log("string [%@] cannot be represented as a double", log: OSLog.default, type: .error, self)
return nil
}
let now = Int(Date().timeIntervalSince1970)
os_log("unix timestamp for now: %i", log: OSLog.default, type: .debug, now)
let oneYear: Int = 31_536_000
let numberOfYears: Int = 100
let upperBound = now + (oneYear * numberOfYears)
let lowerBound = now - (oneYear * numberOfYears)
if Int(timeInterval) > lowerBound && Int(timeInterval) < upperBound {
os_log("unix timestamp within +/- %i years", log: OSLog.default, type: .debug, numberOfYears)
let date = Date(timeIntervalSince1970: timeInterval)
let formatter = DateFormatter.iso8601DateFormatter
return formatter.string(from: date) as NSString
}
os_log("unix timestamp NOT within +/- %i years", log: OSLog.default, type: .debug, numberOfYears)
return nil
}
}
| 31.312925 | 132 | 0.675646 |
18ca6e6c519b1dffd64c85184249fa325aafed1e | 8,616 | // The MIT License (MIT)
// Copyright © 2020 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
SPPermissions: Interface for get ready-use present styles and basic services.
*/
public enum SPPermissions {
// MARK: - Present Styles
/**
SPPermissions: Request permissions with native style without any special controller.
- parameter permissions: List if permissions for request, using model `SPPermissions.Permission`.
*/
@available(iOSApplicationExtension, unavailable)
public static func native(_ permissions: [SPPermissions.Permission]) -> SPPermissionsNativeController {
let controller = SPPermissionsNativeController(prepare(permissions))
return controller
}
#if os(iOS)
/**
SPPermissions: Request permissions as list style.
- parameter permissions: List if permissions for request, using model `SPPermissions.Permission`.
*/
@available(iOSApplicationExtension, unavailable)
public static func list(_ permissions: [SPPermissions.Permission]) -> SPPermissionsListController {
let controller = SPPermissionsListController(prepare(permissions))
return controller
}
/**
SPPermissions: Request permissions as dialog style.
- parameter permissions: List if permissions for request, using model `SPPermissions.Permission`.
*/
@available(iOSApplicationExtension, unavailable)
public static func dialog(_ permissions: [SPPermissions.Permission]) -> SPPermissionsDialogController {
let controller = SPPermissionsDialogController(prepare(permissions))
return controller
}
#endif
// MARK: - Helpers
static func prepare(_ permissions: [SPPermissions.Permission]) -> [SPPermissions.Permission] {
for duplicate in permissions.duplicates {
console("Got duplicate permission \(duplicate.debugName), it will be filtered")
}
for unvailable in permissions.filter({ !$0.canBePresentWithCustomInterface }) {
console("Permission \(unvailable.debugName) can't be present with custom interface. Use `SPPermissions.Permission.NAME.request()` with requerid parametrs. Permission \(unvailable.debugName) will be filtered")
}
return permissions.removedDuplicates().filter({ $0.canBePresentWithCustomInterface })
}
static func console( _ message: String) {
print("SPPermissions: \(message).")
}
// MARK: - Models
/**
SPPermissions: Basic permission model.
Using like enum for list of permissions.
All permissions will be adding to this class like static.
*/
open class Permission: Equatable {
open var authorized: Bool {
return status == .authorized
}
open var denied: Bool {
return status == .denied
}
open var notDetermined: Bool {
return status == .notDetermined
}
/**
SPPermissions: Internal name for permissions.
Don't use it in your interface. Only for console debug.
*/
open var debugName: String {
return type.name
}
/**
SPPermissions: Localized name of permission.
Allowed using in interface.
*/
open var localisedName: String {
return Texts.permission_name(type)
}
/**
SPPermissions: Icon of permission.
*/
open var iconImage: UIImage {
return Images.permission_icon(for: type)
}
/**
SPPermissions: Open settings page.
For most permissions its app page in settings app.
You can overide it if your permission need open custom page.
*/
@available(iOSApplicationExtension, unavailable)
open func openSettingPage() {
DispatchQueue.main.async {
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: nil)
}
}
}
// MARK: Must Ovveride
/**
SPPermissions: Permission type.
*/
open var type: PermissionType {
preconditionFailure("This method must be overridden.")
}
/**
SPPermissions: Authorization status of permission.
*/
open var status: PermissionStatus {
preconditionFailure("This method must be overridden.")
}
/**
SPPermissions: Call request of permission in system.
*/
open func request(completion: @escaping ()->Void) {
preconditionFailure("This method must be overridden.")
}
// MARK: Internal
public static func == (lhs: SPPermissions.Permission, rhs: SPPermissions.Permission) -> Bool {
return lhs.type == rhs.type
}
/**
SPPermissions: If flag is `false`, permission will be filtered if try present in ready-use controllers.
*/
open var canBePresentWithCustomInterface: Bool {
return true
}
public init() {}
}
/**
SPPermissions: Permissions authorization status.
*/
@objc public enum PermissionStatus: Int {
case authorized
case denied
case notDetermined
case notSupported
}
/**
SPPermissions: Permissions type.
Type using like identifier for each permission.
*/
@objc public enum PermissionType: Int {
case camera = 0
case notification = 2
case photoLibrary = 1
case microphone = 3
case calendar = 4
case contacts = 5
case reminders = 6
case speech = 7
case locationWhenInUse = 9
case locationAlways = 10
case motion = 11
case mediaLibrary = 12
case bluetooth = 13
case tracking = 14
case faceID = 15
case siri = 16
case health = 17
public var name: String {
switch self {
case .camera:
return "Camera"
case .photoLibrary:
return "Photo Library"
case .microphone:
return "Microphone"
case .calendar:
return "Calendar"
case .contacts:
return "Contacts"
case .reminders:
return "Reminders"
case .speech:
return "Speech"
case .locationAlways:
return "Location Always"
case .motion:
return "Motion"
case .mediaLibrary:
return "Media Library"
case .bluetooth:
return "Bluetooth"
case .notification:
return "Notification"
case .locationWhenInUse:
return "Location When Use"
case .tracking:
return "Tracking"
case .faceID:
return "FaceID"
case .siri:
return "Siri"
case .health:
return "Health"
}
}
}
}
| 32.636364 | 220 | 0.59494 |
3ac6cc032ce1818c0126915838ce0f1c5dca3e16 | 9,002 | //
// FollowingViewController.swift
// Recipe-CICCC
//
// Created by 北島 志帆美 on 2020-04-09.
// Copyright © 2020 Argus Chen. All rights reserved.
//
import UIKit
import Firebase
import Crashlytics
class FollowingViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var followingsID:[String] = []
var followings:[User] = []
var followingOrNot = [Int:Bool]()
var followingsImages:[Int:UIImage] = [:]
var searchedFollowings:[User] = []
var searchedFollowingsImages:[Int:UIImage] = [:]
let userDataManager = UserdataManager()
let dataManager = FollowingFollowerDataManager()
var searchingWord : String = "" {
didSet {
var count = 0
guard searchingWord != "" else {
return
}
searchedFollowingsImages.removeAll()
searchedFollowings.removeAll()
for (index, user) in followings.enumerated() {
if user.name.lowercased().contains(searchingWord.lowercased()) {
searchedFollowings.append(user)
searchedFollowingsImages[count] = followingsImages[index]
count += 1
}
}
}
}
var parentVC: FollowerFollowingPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.searchBar.delegate = self
self.tableView.dataSource = self
self.tableView.delegate = self
// userDataManager.delegateFollowerFollowing = self
dataManager.delegate = self
parentVC = self.parent as? FollowerFollowingPageViewController
followingsID = parentVC!.followingsID
dataManager.getFollowersFollowings(IDs: self.followingsID, followerOrFollowing: "following")
followingsID.enumerated().map {
dataManager.getFollwersFollowingsImage(uid: $0.1, index: $0.0)
}
self.navigationItem.title = "Following"
for index in 0 ..< followingsID.count {
followingOrNot[index] = true
}
tableView.tableFooterView = UIView()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.navigationController == nil {
//view controller was dismissed
for index in 0 ..< followings.count {
if followingOrNot[index] == false {
dataManager.unfollowing(user: followings[index])
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func followingManagement(_ sender: UIButton) {
let cell = sender.superview?.superview as! followingUserTableViewCell
let indexPath = tableView.indexPath(for: cell)
if followingOrNot[indexPath!.row] == true {
followingOrNot[indexPath!.row] = false
sender.setTitle("Following", for: .normal)
sender.setTitleColor(.white, for: .normal)
sender.backgroundColor = .orange
} else {
followingOrNot[indexPath!.row] = true
sender.setTitle("Unfollow", for: .normal)
sender.backgroundColor = .white
sender.setTitleColor(#colorLiteral(red: 1, green: 0.6430701613, blue: 0, alpha: 1), for: .normal)
sender.layer.borderWidth = 2
sender.layer.borderColor = #colorLiteral(red: 1, green: 0.6430701613, blue: 0, alpha: 1)
}
print(followingOrNot)
}
}
extension FollowingViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchedFollowings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = (tableView.dequeueReusableCell(withIdentifier: "followingUser") as? followingUserTableViewCell)!
cell.delegate = self
cell.userID = searchedFollowings[indexPath.row].userID
cell.userNameLabel.text = searchedFollowings[indexPath.row].name
if parentVC?.userID != Auth.auth().currentUser?.uid {
cell.followingButton.isHidden = true
cell.userManageButton.isHidden = true
} else {
cell.userManageButton.isHidden = false
cell.followingButton.setTitle("Following", for: .normal)
}
if searchedFollowings.count == searchedFollowingsImages.count{
cell.imgView.image = searchedFollowingsImages[indexPath.row]
}
return cell
}
}
extension FollowingViewController:UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searchedFollowings[indexPath.row].userID == Auth.auth().currentUser!.uid {
let vc = UIStoryboard(name: "MyPage", bundle: nil).instantiateViewController(identifier: "User profile") as! MyPageViewController
navigationController?.pushViewController(vc, animated: true)
} else {
let vc = UIStoryboard(name: "creatorProfile", bundle: nil).instantiateViewController(identifier: "creatorProfile") as! CreatorProfileViewController
vc.id = searchedFollowings[indexPath.row].userID
navigationController?.pushViewController(vc, animated: true)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension FollowingViewController: FollowingFollowerManagerDelegate {
func assginFollowersFollowingsImages(image: UIImage, index: Int) {
self.followingsImages[index] = image
self.searchedFollowingsImages[index] = image
self.tableView.reloadData()
}
func assignFollowersFollowings(users: [User]) {
self.followings = users
self.searchedFollowings = users
self.tableView.reloadData()
}
}
extension FollowingViewController: userManageDelegate {
func pressedUserManageButton(uid: String) {
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: alertStyle)
let blockAction = UIAlertAction(title: "Block", style: .default, handler: { action in
self.userDataManager.blockCreators(userID: uid)
self.tableView.reloadData()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
self.dismiss(animated: true, completion: nil)
})
actionSheet.addAction(blockAction)
actionSheet.addAction(cancelAction)
actionSheet.modalPresentationStyle = .popover
self.present(actionSheet, animated: true, completion: nil)
}
}
extension FollowingViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// let pageController = self.children[0] as! SearchingPageViewController
searchingWord = searchBar.text!
if searchingWord == "" {
searchedFollowings.removeAll()
searchedFollowingsImages.removeAll()
searchedFollowingsImages = followingsImages
searchedFollowings = followings
tableView.reloadData()
}
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchingWord = searchBar.text!
searchBar.resignFirstResponder()
}
}
| 33.217712 | 160 | 0.604754 |
298416e43ab753a96b022ffa360360cb256f64e3 | 5,662 | //
// ViewController.swift
// Prework
//
// Created by Abhinav Varre on 12/30/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipDisplayLabel: UILabel!
@IBOutlet weak var totalDisplayLabel: UILabel!
let NUM_SECONDS_UNTIL_RESET = 600.0
let defaults = UserDefaults.standard
var numAppeared = 0;
override func viewDidLoad() {
print("VIEW DID LOAD METHOD ***********")
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Tip Calculator"
let prevEndTime = (defaults.object(forKey: "appCloseTime") as? NSDate) ?? NSDate()
print(prevEndTime)
let elapsedTime = abs(prevEndTime.timeIntervalSinceNow)
defaults.set(elapsedTime, forKey: "elapsedTime")
defaults.synchronize()
print("This is the elapsed time after closing and opening: \(elapsedTime)")
print("The time: \(defaults.double(forKey: "elapsedTime"))")
if(defaults.double(forKey: "elapsedTime") < NUM_SECONDS_UNTIL_RESET)
{
billAmountTextField.text = defaults.string(forKey: "mostRecentUserEntry")
}
else
{
totalLabel.alpha = 0;
tipAmountLabel.alpha = 0;
tipDisplayLabel.alpha = 0;
totalDisplayLabel.alpha = 0;
}
billAmountTextField.becomeFirstResponder()
}
@IBAction func calculate(_ sender: Any) {
calculate()
}
@IBAction func calculateInitial(_ sender: Any) {
calculate()
}
@IBAction func textFieldChanged(_ sender: Any) {
if(billAmountTextField.text == "")
{
finishAnimations()
}
}
@IBAction func animateTotals(_ sender: Any) {
UIView.animate(withDuration:0.4, animations: {
// This causes first view to fade in and second view to fade out
self.totalLabel.alpha = 1
self.tipAmountLabel.alpha = 1
self.tipDisplayLabel.alpha = 1;
self.totalDisplayLabel.alpha = 1;
})
}
func finishAnimations() {
UIView.animate(withDuration:0.4, animations: {
// This causes first view to fade in and second view to fade out
self.totalLabel.alpha = 0
self.tipAmountLabel.alpha = 0
self.tipDisplayLabel.alpha = 0;
self.totalDisplayLabel.alpha = 0;
})
}
func calculate()
{
let bill = Double(billAmountTextField.text!) ?? 0
let tipPercentages = [defaults.double(forKey: "tipOneDef"),defaults.double(forKey: "tipTwoDef"),defaults.double(forKey: "tipThreeDef")];
print(tipControl.selectedSegmentIndex)
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .currency
let tip = formatter.string(for: bill*tipPercentages[tipControl.selectedSegmentIndex])!
let total = formatter.string(for: bill*tipPercentages[tipControl.selectedSegmentIndex]+bill )!
defaults.set(billAmountTextField.text, forKey: "mostRecentUserEntry")
defaults.set(tipControl.selectedSegmentIndex, forKey: "mostRecentPercentage")
tipAmountLabel.text = String(format: "\(tip)")
totalLabel.text = String(format: "\(total)")
}
override func viewWillAppear(_ animated: Bool) {
numAppeared+=1
super.viewWillAppear(animated)
print("view will appear")
// This is a good place to retrieve the default tip percentage from UserDefaults
// and use it to update the tip amount
tipControl.removeAllSegments();
tipControl.insertSegment(withTitle: "\(100 * defaults.double(forKey: "tipOneDef"))%", at: 0, animated: true)
tipControl.insertSegment(withTitle: "\(100 * defaults.double(forKey: "tipTwoDef"))%", at: 1, animated: true)
tipControl.insertSegment(withTitle: "\(100 * defaults.double(forKey: "tipThreeDef"))%", at: 2, animated: true)
print("This is the num of times appeared \(numAppeared)")
if(defaults.double(forKey: "elapsedTime") > NUM_SECONDS_UNTIL_RESET || numAppeared > 1)
{
if(defaults.integer(forKey: "selectedIndex") != -1)
{
tipControl.selectedSegmentIndex = defaults.integer(forKey: "selectedIndex")
}
else
{
tipControl.selectedSegmentIndex = 0;
}
}
else
{
print("This should run because the time is less than 60 seconds")
let selectedIndex = defaults.integer(forKey: "mostRecentPercentage")
if(selectedIndex == -1)
{
tipControl.selectedSegmentIndex = defaults.integer(forKey: "selectedIndex")
}
else
{
tipControl.selectedSegmentIndex = selectedIndex
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did appear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("view will disappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did disappear")
}
}
| 34.315152 | 144 | 0.612151 |
18f48bbfd529b83d5baca6c69df0561af2f6f4c6 | 3,043 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** The context, or state, associated with a message. */
public struct Context: JSONEncodable, JSONDecodable {
/// The raw JSON object used to construct this model.
public let json: [String: Any]
/// The unique identifier of the conversation.
public let conversationID: String
/// A system object that includes information about the dialog.
public let system: System
/// Used internally to initialize a `Context` model from JSON.
public init(json: JSON) throws {
self.json = try json.getDictionaryObject()
conversationID = try json.getString(at: "conversation_id")
system = try json.decode(at: "system", type: System.self)
}
/// Used internally to serialize a `Context` model to JSON.
public func toJSONObject() -> Any {
return json
}
}
/** A system object that includes information about the dialog. */
public struct System: JSONEncodable, JSONDecodable {
/// The raw JSON object used to construct this model.
public let json: [String: Any]
/// An array of dialog node ids that are in focus in the conversation. If no node is in the
/// list, the conversation restarts at the root with the next request. If multiple dialog nodes
/// are in the list, several dialogs are in progress, and the last ID in the list is active.
/// When the active dialog ends, it is removed from the stack and the previous one becomes
/// active.
public let dialogStack: [String]
/// The number of cycles of user input and response in this conversation.
public let dialogTurnCounter: Int
/// The number of inputs in this conversation. This counter might be higher than the
/// `dialogTurnCounter` when multiple inputs are needed before a response can be returned.
public let dialogRequestCounter: Int
/// Used internally to initialize a `System` model from JSON.
public init(json: JSON) throws {
self.json = try json.getDictionaryObject()
dialogStack = try json.getArray(at: "dialog_stack").map { try $0.getString(at: "dialog_node") }
dialogTurnCounter = try json.getInt(at: "dialog_turn_counter")
dialogRequestCounter = try json.getInt(at: "dialog_request_counter")
}
/// Used internally to serialize a `System` model to JSON.
public func toJSONObject() -> Any {
return json
}
}
| 39.012821 | 103 | 0.693395 |
9bcc61b6ef1874d567c4d6a8dd91ef95c0ca5606 | 1,349 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
@available(iOS 13.0, *)
func application(
_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(
name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
@available(iOS 13.0, *)
func application(
_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>
) {
// Called when the user discards a scene session. If any sessions were discarded while the
// application was not running, this will be called shortly after
// application:didFinishLaunchingWithOptions. Use this method to release any resources
// that were specific to the discarded scenes, as they will not return.
}
}
| 33.725 | 100 | 0.750927 |
ac157ec24c21f835a008e45b4036fe5a1d3a0eec | 1,404 | /// Copyright © 2018 Zaid M. Said
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
struct CustomCell {
let identifier: String
let content: Any
let height: CGFloat?
init(identifier: String, content: Any, height: CGFloat?) {
self.identifier = identifier
self.content = content
self.height = height
}
}
| 41.294118 | 81 | 0.729345 |
9bc1e18e4e900b4ea62c8de77e9e3fc050de54e7 | 253 | //
// Config.swift
// MyPowerOf10
//
// Created by John Sanderson on 06/11/2017.
// Copyright © 2017 JohnSanderson. All rights reserved.
//
import Foundation
struct Config {
static let baseURL = URL(string: "http://www.powerof10.info")!
}
| 15.8125 | 64 | 0.671937 |
1a6e01edb5518e8b4558deb279181a50fee23fac | 500 | //
// ViewController.swift
// MsgBox
//
// Created by hengjia0 on 12/28/2019.
// Copyright (c) 2019 hengjia0. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20 | 80 | 0.668 |
91531632b6fcae26af96df518f09ff6357741c4d | 2,081 | //
// UserResponse.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A User Object */
public struct UserResponse: Codable, Hashable {
/** The unique ID of the User */
public var pkiUserID: Int
/** The unique ID of the Language. Valid values: |Value|Description| |-|-| |1|French| |2|English| */
public var fkiLanguageID: Int
public var eUserType: FieldEUserType
/** The First name of the user */
public var sUserFirstname: String
/** The Last name of the user */
public var sUserLastname: String
/** The Login name of the User. */
public var sUserLoginname: String
public var objAudit: CommonAudit
public init(pkiUserID: Int, fkiLanguageID: Int, eUserType: FieldEUserType, sUserFirstname: String, sUserLastname: String, sUserLoginname: String, objAudit: CommonAudit) {
self.pkiUserID = pkiUserID
self.fkiLanguageID = fkiLanguageID
self.eUserType = eUserType
self.sUserFirstname = sUserFirstname
self.sUserLastname = sUserLastname
self.sUserLoginname = sUserLoginname
self.objAudit = objAudit
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case pkiUserID
case fkiLanguageID
case eUserType
case sUserFirstname
case sUserLastname
case sUserLoginname
case objAudit
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(pkiUserID, forKey: .pkiUserID)
try container.encode(fkiLanguageID, forKey: .fkiLanguageID)
try container.encode(eUserType, forKey: .eUserType)
try container.encode(sUserFirstname, forKey: .sUserFirstname)
try container.encode(sUserLastname, forKey: .sUserLastname)
try container.encode(sUserLoginname, forKey: .sUserLoginname)
try container.encode(objAudit, forKey: .objAudit)
}
}
| 33.031746 | 174 | 0.691014 |
3a159ac82b135f3f0e40381d852af62f7b6eb370 | 2,044 | //
// HorizontalListCell.swift
// Example
//
// Created by Pedro M. Zaroni on 05/07/20.
// Copyright © 2020 mugbug. All rights reserved.
//
import UIKit
import PaintAndBrush
import BricksAndTiles
final class HorizontalListCell: UITableViewCell, Reusable {
var dataSource: CollectionViewDataSource?
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: flowLayout()
)
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = .clear
return collectionView
}()
private func flowLayout() -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = .init(top: 0, left: 16, bottom: 0, right: 16)
// Uncomment to show header
// layout.headerReferenceSize = CGSize(width: 100, height: 50)
layout.scrollDirection = .horizontal
return layout
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
buildView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension HorizontalListCell: ViewCodeProtocol {
func setupHierarchy() {
contentView.addSubviewWithConstraints(
subview: collectionView,
insets: .init(
top: 16,
left: 0,
bottom: -16,
right: 0
)
)
}
func setupConstraints() { }
func additionalSetup() {
let factory = HorizontalListFactory(cellSize: cellSize).make()
self.dataSource = CollectionViewDataSource(
sections: factory,
collectionView: collectionView
)
}
func cellSize(collectionSize: CGSize) -> CGSize {
let height = collectionSize.height
return CGSize(width: height, height: height)
}
}
| 27.621622 | 79 | 0.632583 |
ef14c780d19045db72887bb135ebf6e96c10dc2b | 1,116 | //
// Store.swift
// GithubSearch
//
// Created by Majid Jabrayilov on 9/16/19.
// Copyright © 2019 Majid Jabrayilov. All rights reserved.
//
import Foundation
import Combine
typealias Reducer<State, Action, Environment> =
(inout State, Action, Environment) -> AnyPublisher<Action, Never>?
final class Store<State, Action, Environment>: ObservableObject {
@Published private(set) var state: State
private let environment: Environment
private let reducer: Reducer<State, Action, Environment>
private var effectCancellables: Set<AnyCancellable> = []
init(
initialState: State,
reducer: @escaping Reducer<State, Action, Environment>,
environment: Environment
) {
self.state = initialState
self.reducer = reducer
self.environment = environment
}
func send(_ action: Action) {
guard let effect = reducer(&state, action, environment) else {
return
}
effect
.receive(on: DispatchQueue.main)
.sink(receiveValue: send)
.store(in: &effectCancellables)
}
}
| 26.571429 | 70 | 0.650538 |
61097238e1eec97a04a4464268401061a9aaeac4 | 2,170 | //
// AppDelegate.swift
// Tumblr
//
// Created by Dominic Pham on 9/4/18.
// Copyright © 2018 Dominic Pham. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.170213 | 285 | 0.754839 |
7663c731fc49d8c0efaf8ae3de85ecd27545cb1f | 1,574 | //
// KeyboardButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-04-26.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
/**
This protocol can be implemented by views that can be added
to button rows and collection views.
For convenience, you can use the `KeyboardButtonView` class
instead of implementing this protocol from scratch.
*/
public protocol KeyboardButton: KeyboardButtonRowComponent {
var action: KeyboardAction { get }
var secondaryAction: KeyboardAction? { get }
}
// MARK: - Animations
public extension KeyboardButton {
func animateStandardPress(factor: CGFloat = 1.1, completion: (() -> Void)? = nil) {
let transform = CGAffineTransform(scaleX: factor, y: factor)
animateTransform(transform, completion: completion)
}
func animateStandardRelease(completion: (() -> Void)? = nil) {
animateTransform(.identity, completion: completion)
}
func animateStandardTap(completion: (() -> Void)? = nil) {
animateStandardPress { [weak self] in
self?.animateStandardRelease(completion: completion)
}
}
}
private extension KeyboardButton {
func animateTransform(_ transform: CGAffineTransform, completion: (() -> Void)? = nil) {
UIView.animate(
withDuration: 0.1,
delay: 0,
options: [.curveEaseOut, .allowUserInteraction],
animations: { [weak self] in self?.transform = transform },
completion: { _ in completion?() }
)
}
}
| 27.614035 | 92 | 0.650572 |
e8dee3bba4eead8edcdbf90804926508bc020417 | 1,442 | import UIKit
import SnapKit
import ThemeKit
class MarkdownHeader3Cell: UITableViewCell {
private static let topPadding: CGFloat = .margin6x
private static let bottomPadding: CGFloat = .margin3x
private static let horizontalPadding: CGFloat = .margin6x
private let textView = MarkdownTextView()
override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
contentView.addSubview(textView)
textView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview().inset(MarkdownHeader3Cell.horizontalPadding)
maker.top.equalToSuperview().inset(MarkdownHeader3Cell.topPadding)
maker.bottom.equalToSuperview().inset(MarkdownHeader3Cell.bottomPadding)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(attributedString: NSAttributedString) {
textView.attributedText = attributedString
}
}
extension MarkdownHeader3Cell {
static func height(containerWidth: CGFloat, attributedString: NSAttributedString) -> CGFloat {
let textWidth = containerWidth - 2 * horizontalPadding
let textHeight = attributedString.height(containerWidth: textWidth)
return topPadding + textHeight + bottomPadding
}
}
| 32.044444 | 98 | 0.726075 |
29e0d7710730f88d3f4feba6864e33f878bdc95c | 1,233 | //
// DouyuZhiboUITests.swift
// DouyuZhiboUITests
//
// Created by 雨滴 on 17/1/17.
// Copyright © 2017年 雨滴. All rights reserved.
//
import XCTest
class DouyuZhiboUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.324324 | 182 | 0.660989 |
ab9178e1ef3be492e59a8cf3b106969a0bd1ba84 | 2,167 | //
// AppDelegate.swift
// Kml-Mapbox
//
// Created by Greg Pardo on 12/28/16.
// Copyright © 2016 asus4. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.754499 |
46039cefd346abbd915695b545cef76ac6ac8fd5 | 1,809 | //
// _BaseNavigationController.swift
// FirebaseQuery
//
// Created by William on 2019/6/13.
// Copyright © 2019 William. All rights reserved.
//
import UIKit
// MARK: - 基礎的NavigationController
class _BaseNavigationController: UINavigationController {
var newType: TabBarType = .cart
var newTitle: String = String()
override func viewDidLoad() {
super.viewDidLoad()
initSetting(type: newType, title: newTitle)
}
}
// MARK: - 小工具
extension _BaseNavigationController {
/// 設定基本變數
fileprivate func configure(type: TabBarType, title: String) {
newType = type
newTitle = title
}
/// 設定下一個ViewController的初始型態
private func initSetting(type: TabBarType, title: String) {
let viewController = viewControllers.first as? ProductActionViewController
viewController?.tabBarType = type
viewController?.navigationItemTitle = title
}
}
// MARK: - StockNavigationController
class StockNavigationController: _BaseNavigationController {
override func viewDidLoad() {
configure(type: .cart, title: "新品")
super.viewDidLoad()
}
}
// MARK: - PlusNavigationController
class PlusNavigationController: _BaseNavigationController {
override func viewDidLoad() {
configure(type: .plus, title: "進貨")
super.viewDidLoad()
}
}
// MARK: - MinusNavigationController
class MinusNavigationController: _BaseNavigationController {
override func viewDidLoad() {
configure(type: .minus, title: "出貨")
super.viewDidLoad()
}
}
// MARK: - FixNavigationController
class FixNavigationController: _BaseNavigationController {
override func viewDidLoad() {
configure(type: .fix, title: "更新")
super.viewDidLoad()
}
}
| 24.445946 | 82 | 0.674959 |
79303229ce1039d66b2d183fb35e463c3d9d1a2b | 10,959 | import XCTest
import Nimble
@testable import Osusume
class NavigationRouterTest: XCTestCase {
var navigationRouter: NavigationRouter!
var rootNavController: UINavigationController!
var fakeSessionRepo: FakeSessionRepo!
override func setUp() {
rootNavController = UINavigationController()
fakeSessionRepo = FakeSessionRepo()
navigationRouter = NavigationRouter(
navigationController: rootNavController,
sessionRepo: fakeSessionRepo,
restaurantRepo: FakeRestaurantRepo(),
photoRepo: FakePhotoRepo(),
userRepo: FakeUserRepo(),
commentRepo: FakeCommentRepo(),
cuisineRepo: FakeCuisineRepo(),
likeRepo: FakeLikeRepo(),
priceRangeRepo: FakePriceRangeRepo(),
restaurantSearchRepo: FakeRestaurantSearchRepo(),
animated: false
)
}
func test_showingNewRestaurantScreen() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.pushViewController(UIViewController(), animated: false)
navigationRouter.showNewRestaurantScreen()
let newRestaurantNavController = rootNavController.presentedViewController as? UINavigationController
expect(newRestaurantNavController?.topViewController).to(beAKindOf(NewRestaurantViewController))
}
func test_showingRestaurantListScreen() {
navigationRouter.showRestaurantListScreen()
expect(self.rootNavController.topViewController).to(beAKindOf(RestaurantListViewController))
}
func test_showingRestaurantDetailScreen() {
navigationRouter.showRestaurantDetailScreen(1)
expect(self.rootNavController.topViewController).to(beAKindOf(RestaurantDetailViewController))
}
func test_showingEditRestaurantScreen() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.pushViewController(UIViewController(), animated: false)
let restaurant = RestaurantFixtures.newRestaurant()
navigationRouter.showEditRestaurantScreen(restaurant)
let editRestaurantNavController = rootNavController.presentedViewController as? UINavigationController
expect(editRestaurantNavController?.topViewController).to(beAKindOf(EditRestaurantViewController))
}
func test_showingLoginScreen() {
navigationRouter.showLoginScreen()
expect(self.rootNavController.topViewController).to(beAKindOf(LoginViewController))
}
func test_passesSessionRepo_toTheLoginScreen() {
navigationRouter.showLoginScreen()
let loginVC = rootNavController.topViewController as! LoginViewController
let loginSessionRepo = loginVC.sessionRepo as! FakeSessionRepo
expect(self.fakeSessionRepo === loginSessionRepo).to(beTrue())
}
func test_showingNewCommentScreen() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.pushViewController(UIViewController(), animated: false)
navigationRouter.showNewCommentScreen(1)
let newCommentNavController = rootNavController.presentedViewController as? UINavigationController
expect(newCommentNavController?.topViewController).to(beAKindOf(NewCommentViewController))
}
func test_showingImageScreen() {
let url = NSURL(string: "my-awesome-url")!
navigationRouter.showImageScreen(url)
expect(self.rootNavController.topViewController).to(beAKindOf(ImageViewController))
expect((self.rootNavController.topViewController as! ImageViewController).url)
.to(equal(url))
}
func test_showingMapScreen_presentsMapViewController() {
navigationRouter.showMapScreen(1.23, longitude: 2.34)
expect(self.rootNavController.topViewController).to(beAKindOf(MapViewController))
}
func test_showingCuisineListScreen() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.setViewControllers(
[UIViewController()],
animated: false
)
let newRestaurantVC = NewRestaurantViewController(
router: navigationRouter,
restaurantRepo: FakeRestaurantRepo(),
photoRepo: FakePhotoRepo(),
reloader: FakeReloader()
)
let newRestaurantNavVC = UINavigationController(
rootViewController: newRestaurantVC
)
rootNavController.presentViewController(
newRestaurantNavVC,
animated: false,
completion: nil
)
navigationRouter.showFindCuisineScreen(newRestaurantVC)
expect(newRestaurantNavVC.topViewController).to(beAKindOf(CuisineListViewController))
}
func test_dismissPresentedNavigationController_dismissesPresentedNavigationController() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.pushViewController(UIViewController(), animated: false)
let modalNavController = UINavigationController(rootViewController: UIViewController())
rootNavController.presentViewController(
modalNavController,
animated: false,
completion: nil
)
let presentedNavController = rootNavController.presentedViewController as? UINavigationController
expect(presentedNavController?.topViewController).toNot(beNil())
navigationRouter.dismissPresentedNavigationController()
NSRunLoop.osu_advance(by: 1)
expect(self.rootNavController.presentedViewController).to(beNil())
}
func test_dismissPresentedNavigationController_doesNotDismissPresentedViewController() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.pushViewController(UIViewController(), animated: false)
rootNavController.presentViewController(
UIViewController(),
animated: false,
completion: nil
)
let presentedViewController = rootNavController.presentedViewController
expect(presentedViewController).toNot(beNil())
navigationRouter.dismissPresentedNavigationController()
NSRunLoop.osu_advance(by: 1)
expect(self.rootNavController.presentedViewController).to(equal(presentedViewController))
}
func test_showingPriceRangeListScreen() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.setViewControllers(
[UIViewController()],
animated: false
)
let newRestaurantVC = NewRestaurantViewController(
router: navigationRouter,
restaurantRepo: FakeRestaurantRepo(),
photoRepo: FakePhotoRepo(),
reloader: FakeReloader()
)
let newRestaurantNavVC = UINavigationController(
rootViewController: newRestaurantVC
)
rootNavController.presentViewController(
newRestaurantNavVC,
animated: false,
completion: nil
)
navigationRouter.showPriceRangeListScreen(newRestaurantVC)
expect(newRestaurantNavVC.topViewController).to(beAKindOf(PriceRangeListViewController))
}
func test_showingFindRestaurantScreen_withNewViewController_isOK() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.setViewControllers(
[UIViewController()],
animated: false
)
let newRestaurantVC = NewRestaurantViewController(
router: FakeRouter(),
restaurantRepo: FakeRestaurantRepo(),
photoRepo: FakePhotoRepo(),
reloader: FakeReloader()
)
let newRestaurantNavVC = UINavigationController(
rootViewController: newRestaurantVC
)
rootNavController.presentViewController(
newRestaurantNavVC,
animated: false,
completion: nil
)
navigationRouter.showFindRestaurantScreen(newRestaurantVC)
expect(newRestaurantNavVC.topViewController).to(beAKindOf(FindRestaurantViewController))
}
func test_showingFindRestaurantScreen_withEditViewController_isOK() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.setViewControllers(
[UIViewController()],
animated: false
)
let restaurant = RestaurantFixtures.newRestaurant(
id: 5,
name: "Pizzakaya",
liked: false,
cuisine: Cuisine(id: 1, name: "American"),
notes: "The best pizza in Tokyo",
createdByUser: (id: 99, name: "Witta", email: "witta@pivotal"),
priceRange: PriceRange(id: 1, range: "Reasonable"),
photoUrls: [
PhotoUrl(id: 10, url: NSURL(string: "url")!)
]
)
let editRestaurantVC = EditRestaurantViewController(
router: FakeRouter(),
repo: FakeRestaurantRepo(),
photoRepo: FakePhotoRepo(),
sessionRepo: fakeSessionRepo,
reloader: FakeReloader(),
restaurant: restaurant
)
let editRestaurantNavVC = UINavigationController(
rootViewController: editRestaurantVC
)
rootNavController.presentViewController(
editRestaurantNavVC,
animated: false,
completion: nil
)
navigationRouter.showFindRestaurantScreen(editRestaurantVC)
expect(editRestaurantNavVC.topViewController).to(beAKindOf(FindRestaurantViewController))
}
func test_popViewControllerOffStack_popsViewControllerOffOfRootVC() {
let vc1 = UIViewController()
let vc2 = UIViewController()
rootNavController.setViewControllers(
[vc1, vc2],
animated: false
)
navigationRouter.popViewControllerOffStack()
expect(self.rootNavController.topViewController === vc1).to(beTrue())
}
func test_popViewControllerOffStack_popsViewControllerOffOfPresentedVC() {
configureUIWindowWithRootViewController(rootNavController)
rootNavController.setViewControllers(
[UIViewController()],
animated: false
)
let vc1 = UIViewController()
let vc2 = UIViewController()
let presentedNavController = UINavigationController()
presentedNavController.setViewControllers(
[vc1, vc2],
animated: false
)
rootNavController.presentViewController(
presentedNavController,
animated: false,
completion: nil
)
navigationRouter.popViewControllerOffStack()
expect(presentedNavController.topViewController === vc1).to(beTrue())
}
}
| 33.411585 | 110 | 0.686376 |
14bb47ae35269117ba30e6e3f00b2c3a132f9da7 | 445 | //
// AppDelegate.swift
// PaintCodeKit
//
// Created by alberdev on 05/04/2019.
// Copyright (c) 2019 alberdev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| 21.190476 | 152 | 0.714607 |
ab0aaf71dcd8c33bc5d146ffe8b1f3119021c675 | 2,182 | //
// NumberOf1Bits.swift
// LeetCode.swift
//
// Created by 叶帆 on 2020/6/28.
// Copyright © 2020 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
/**
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Note:
Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above the input represents the signed integer -3.
Follow up:
If this function is called many times, how would you optimize it?
======
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
*/
import Foundation
class Solution {
func hammingWeight(_ n: Int) -> Int {
var res = 0
var n = n
while n > 0 {
res += n & 1
n >>= 1
}
return res
}
}
| 25.372093 | 280 | 0.735564 |
220ee9fdd8f2d7eebcd70873ce809fcff2ad1072 | 9,131 | //
// Copyright (c) 2021 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import UIKit
/// Displays a form for the user to enter details.
/// :nodoc:
@objc(ADYFormViewController)
open class FormViewController: UIViewController, Localizable, KeyboardObserver, Observer, PreferredContentSizeConsumer {
fileprivate enum Animations {
fileprivate static let keyboardBottomInset = "keyboardBottomInset"
fileprivate static let firstResponder = "firstResponder"
}
/// :nodoc:
public var requiresKeyboardInput: Bool { formRequiresInputView() }
/// Indicates the `FormViewController` UI styling.
public let style: ViewStyle
/// :nodoc:
/// Delegate to handle different viewController events.
public weak var delegate: ViewControllerDelegate?
// MARK: - Public
/// Initializes the FormViewController.
///
/// - Parameter style: The `FormViewController` UI style.
public init(style: ViewStyle) {
self.style = style
super.init(nibName: nil, bundle: nil)
startObserving()
}
deinit {
stopObserving()
}
// MARK: - View lifecycle
/// :nodoc:
override open func viewDidLoad() {
super.viewDidLoad()
addFormView()
itemManager.topLevelItemViews.forEach(formView.appendItemView(_:))
delegate?.viewDidLoad(viewController: self)
}
/// :nodoc:
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
delegate?.viewWillAppear(viewController: self)
}
/// :nodoc:
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
delegate?.viewDidAppear(viewController: self)
view.adyen.animate(context: AnimationContext(animationKey: Animations.firstResponder,
duration: 0,
options: [.layoutSubviews, .beginFromCurrentState],
animations: { [weak self] in
self?.assignInitialFirstResponder()
}))
}
/// :nodoc:
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
resignFirstResponder()
}
/// :nodoc:
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
resetForm()
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// :nodoc:
override public var preferredContentSize: CGSize {
get { formView.intrinsicContentSize }
// swiftlint:disable:next unused_setter_value
set { AdyenAssertion.assertionFailure(message: """
PreferredContentSize is overridden for this view controller.
getter - returns minimum possible content size.
setter - no implemented.
""") }
}
// MARK: - KeyboardObserver
/// :nodoc:
public var keyboardObserver: Any?
/// :nodoc:
public func startObserving() {
startObserving { [weak self] in
self?.keyboardRect = $0
self?.didUpdatePreferredContentSize()
}
}
// MARK: - Private Properties
private var keyboardRect: CGRect = .zero
private lazy var itemManager = FormViewItemManager()
// MARK: - PreferredContentSizeConsumer
/// :nodoc:
public func willUpdatePreferredContentSize() { /* Empty implementation */ }
/// :nodoc:
public func didUpdatePreferredContentSize() {
let bottomInset: CGFloat = keyboardRect.height - view.safeAreaInsets.bottom
let context = AnimationContext(animationKey: Animations.keyboardBottomInset,
duration: 0.25,
options: [.beginFromCurrentState, .layoutSubviews],
animations: { [weak self] in
self?.formView.contentInset.bottom = bottomInset
})
view.adyen.animate(context: context)
}
// MARK: - Items
/// Appends an item to the form.
///
/// - Parameters:
/// - item: The item to append.
public func append<T: FormItem>(_ item: T) {
let itemView = itemManager.append(item)
observerVisibility(of: item, and: itemView)
itemView.applyTextDelegateIfNeeded(delegate: self)
addItemViewIfNeeded(itemView)
}
private func addItemViewIfNeeded(_ itemView: AnyFormItemView) {
guard isViewLoaded else { return }
formView.appendItemView(itemView)
}
private func observerVisibility<T: FormItem>(of item: T, and itemView: UIView) {
guard let item = item as? Hidable else { return }
itemView.adyen.hide(animationKey: String(describing: itemView),
hidden: item.isHidden.wrappedValue, animated: false)
observe(item.isHidden) { isHidden in
itemView.adyen.hide(animationKey: String(describing: itemView),
hidden: isHidden, animated: true)
}
}
// MARK: - Localizable
/// :nodoc:
public var localizationParameters: LocalizationParameters?
// MARK: - Validity
/// Validates the items in the form. If the form's contents are invalid, an alert is presented.
///
/// - Returns: Whether the form is valid or not.
public func validate() -> Bool {
let validatableItems = getAllValidatableItems()
let isValid = validatableItems.allSatisfy { $0.isValid() }
// Exit when all validations passed.
guard !isValid else { return true }
resignFirstResponder()
showValidation()
return false
}
/// :nodoc:
public func showValidation() {
itemManager.flatItemViews
.compactMap { $0 as? AnyFormValueItemView }
.forEach { $0.validate() }
}
private func getAllValidatableItems() -> [ValidatableFormItem] {
let visibleItems = itemManager.topLevelItem.filter {
!(($0 as? Hidable)?.isHidden.wrappedValue == true)
}
let validatableItems = visibleItems.flatMap(\.flatSubitems).compactMap { $0 as? ValidatableFormItem }
return validatableItems
}
private func formRequiresInputView() -> Bool {
itemManager.flatItems.contains { $0 is InputViewRequiringFormItem }
}
public func resetForm() {
itemManager.flatItemViews.forEach { $0.reset() }
}
// MARK: - Private
private func addFormView() {
view.addSubview(formView)
view.backgroundColor = style.backgroundColor
formView.backgroundColor = style.backgroundColor
formView.adyen.anchor(inside: view.safeAreaLayoutGuide)
}
private lazy var formView: FormView = {
let form = FormView()
form.translatesAutoresizingMaskIntoConstraints = false
return form
}()
// MARK: - UIResponder
@discardableResult
override public func resignFirstResponder() -> Bool {
let textItemView = itemManager.flatItemViews.first(where: { $0.isFirstResponder })
textItemView?.resignFirstResponder()
return super.resignFirstResponder()
}
// MARK: - Other
private func assignInitialFirstResponder() {
guard view.isUserInteractionEnabled else { return }
let textItemView = itemManager.topLevelItemViews.first(where: { $0.canBecomeFirstResponder })
textItemView?.becomeFirstResponder()
}
}
// MARK: - FormTextItemViewDelegate
extension FormViewController: FormTextItemViewDelegate {
/// :nodoc:
public func didReachMaximumLength<T: FormTextItem>(in itemView: FormTextItemView<T>) {
handleReturnKey(from: itemView)
}
/// :nodoc:
public func didSelectReturnKey<T: FormTextItem>(in itemView: FormTextItemView<T>) {
handleReturnKey(from: itemView)
}
private func handleReturnKey<T: FormTextItem>(from itemView: FormTextItemView<T>) {
let itemViews = itemManager.flatItemViews
// Determine the index of the current item view.
guard let currentIndex = itemViews.firstIndex(where: { $0 === itemView }) else {
return
}
// Create a slice of the remaining item views.
let remainingItemViews = itemViews.suffix(from: itemViews.index(after: currentIndex))
// Find the first item view that's eligible to become a first responder.
let nextItemView = remainingItemViews.first { $0.canBecomeFirstResponder && $0.isHidden == false }
// Assign the first responder, or resign the current one if there is none remaining.
if let nextItemView = nextItemView {
nextItemView.becomeFirstResponder()
} else {
itemView.resignFirstResponder()
}
}
}
| 31.926573 | 120 | 0.624247 |
bfdcf10ea57db83b0af14c1132cd6c9e76ee890a | 2,538 | //
// OptionalLossyArray.swift
//
//
// Created by apploft GmbH on 26.11.21.
//
import Foundation
@propertyWrapper
public struct OptionalLossyArray<T> {
public enum EmptyArrayEncodingStrategy {
case omitKey
case encodeKeyWithNullValue
case encodeKeyWithEmptyArray
}
public var wrappedValue: [T]
public var emptyArrayEncodingStrategy: EmptyArrayEncodingStrategy
public init(wrappedValue: [T], emptyArrayEncodingStrategy: EmptyArrayEncodingStrategy = .omitKey) {
self.wrappedValue = wrappedValue
self.emptyArrayEncodingStrategy = emptyArrayEncodingStrategy
}
}
extension OptionalLossyArray: Decodable where T: Decodable {
private struct AnyDecodableValue: Decodable {}
public init(from decoder: Decoder) throws {
self.emptyArrayEncodingStrategy = .omitKey
do {
var container = try decoder.unkeyedContainer()
var elements: [T] = []
while !container.isAtEnd {
do {
let value = try container.decode(T.self)
elements.append(value)
} catch {
_ = try? container.decode(AnyDecodableValue.self)
}
}
self.wrappedValue = elements
} catch {
self.wrappedValue = []
}
}
}
extension OptionalLossyArray: Encodable where T: Encodable {
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
extension KeyedDecodingContainer {
public func decode<T: Decodable>(_ type: OptionalLossyArray<T>.Type, forKey key: Key) throws -> OptionalLossyArray<T> {
(try? decodeIfPresent(type, forKey: key)) ?? OptionalLossyArray<T>(wrappedValue: [])
}
}
/// Implements the selected EmptyArrayEncodingStrategy
extension KeyedEncodingContainer {
public mutating func encode<T: Encodable>(_ value: OptionalLossyArray<T>, forKey key: Key) throws {
if !value.wrappedValue.isEmpty {
try encodeIfPresent(value, forKey: key)
} else {
switch value.emptyArrayEncodingStrategy {
case .omitKey:
break
case .encodeKeyWithNullValue:
try encodeNil(forKey: key)
case .encodeKeyWithEmptyArray:
try encodeIfPresent(value, forKey: key)
}
}
}
}
extension OptionalLossyArray: Equatable where T: Equatable { }
extension OptionalLossyArray: Hashable where T: Hashable { }
| 28.516854 | 123 | 0.637116 |
d9db1d4075ecd571a6674558ce93e06f9b9469a7 | 2,531 | //
// MemoryCache.swift
// Cache
//
// Created by Nan Wang on 2017-11-30.
// Copyright © 2017 NanTech. All rights reserved.
//
import Foundation
/// Memory cache
final public class MemoryCache {
/// User NSCache as memory cache
private let cache = NSCache<NSString, MemoryCacheWrapper>()
/// Memory configuration
private let configuration: MemoryConfiguration
/// Initialiser
public init(configuration: MemoryConfiguration) {
self.configuration = configuration
self.cache.name = configuration.name
self.cache.countLimit = Int(configuration.countLimit)
self.cache.totalCostLimit = Int(configuration.maxSize)
}
/// Store any Codable object into memory cache
public func setObject<T: Codable>(_ object: T, for key: String) {
self[key] = MemoryCacheWrapper(with: object)
}
/// Retrieve any Codable object from memory cache
public func object<T: Codable>(for key: String) throws -> T {
guard let memoryCacheWrapper = self[key] else {
throw MemoryCacheError.notExist
}
guard let object = memoryCacheWrapper.object as? T else {
throw MemoryCacheError.unexpectedType
}
return object
}
/// Remove object from memory cache
public func removeObject(for key: String) {
cache.removeObject(forKey: NSString(string: key))
}
/// Subscript
public subscript(key: String) -> MemoryCacheWrapper? {
get {
return cache.object(forKey: key as NSString)
}
set {
if let memoryCacheWrapper = newValue {
cache.setObject(memoryCacheWrapper, forKey: key as NSString)
} else {
cache.removeObject(forKey: key as NSString)
}
}
}
}
/// Because `NSCache` can only store `NSObject`,
/// a wrapper is created to be able to store any Codable object, refrence or value type
final public class MemoryCacheWrapper: NSObject {
let object: Codable
init(with object: Codable) {
self.object = object
}
}
/// MemoryCache errors
public enum MemoryCacheError: LocalizedError {
case notExist
case unexpectedType
public var errorDescription: String? {
switch self {
case .notExist: return "[MemoryCache] Object does not exist"
case .unexpectedType: return "[MemoryCache] Object returned does not match the type of object expected"
}
}
}
| 28.438202 | 111 | 0.633742 |
293f0b1237fba875b6c219ac21388d5e1a0fb0c1 | 347 | //
// Copyright © fedulvtubudul, 2020. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
-> Bool {
return true
}
}
| 16.52381 | 86 | 0.760807 |
205d9785b9fdea8c4407bece3ac3e98643f18719 | 8,936 | // Copyright © 2020 Suguru Kishimoto. All rights reserved.
//
import Foundation
import FirebaseRemoteConfig
/// ConfigBridge for `String`
public final class ConfigStringBridge: ConfigBridge<String> {
public typealias T = String
public override func save(key: String, value: String?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].stringValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `Int`
public final class ConfigIntBridge: ConfigBridge<Int> {
public typealias T = Int
public override func save(key: String, value: Int?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].numberValue.intValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `Double`
public final class ConfigDoubleBridge: ConfigBridge<Double> {
public typealias T = Double
public override func save(key: String, value: Double?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].numberValue.doubleValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `Float`
public final class ConfigFloatBridge: ConfigBridge<Float> {
public typealias T = Float
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].numberValue.floatValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `Bool`
public final class ConfigBoolBridge: ConfigBridge<Bool> {
public typealias T = Bool
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].boolValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `Data`
public final class ConfigDataBridge: ConfigBridge<Data> {
public typealias T = Data
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].dataValue
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key] as? T
}
}
/// ConfigBridge for `URL`
public final class ConfigURLBridge: ConfigBridge<URL> {
public typealias T = URL
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value?.absoluteString
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].stringValue.flatMap(URL.init(string:))
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return (defaultsStore[key] as? String).flatMap(URL.init(string:))
}
}
/// ConfigBridge for `UIColor`
public final class ConfigColorBridge: ConfigBridge<UIColor> {
public typealias T = UIColor
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value?.hexString
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].stringValue.flatMap { $0.hexColor }
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return (defaultsStore[key] as? String).flatMap { $0.hexColor }
}
}
/// ConfigBridge for `RawRepresentable`(Enum)
public final class ConfigRawRepresentableBridge<T: RawRepresentable>: ConfigBridge<T> {
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value?.rawValue
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return remoteConfig[key].stringValue.flatMap(deserialize) ?? (remoteConfig[key].numberValue as NSNumber?).flatMap(deserialize)
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return defaultsStore[key].flatMap(deserialize)
}
func deserialize(_ object: Any) -> T? {
return (object as? T.RawValue).flatMap(T.init(rawValue:))
}
}
/// ConfigBridge for `Decodable`
///
/// - note: You can't set default value if a value is `Decodasble` object, not `Encodable` object.
/// If you can set default value, Please make object conform to `Encodable` and use `ConfigCodableBridge`.
///
public final class ConfigDecodableBridge<T: Decodable>: ConfigBridge<T> {
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
}
public override func get(key: String, remoteConfig: RemoteConfig, decoder: JSONDecoder) -> T? {
return deserialize(remoteConfig[key].dataValue, decoder) ??
remoteConfig[key].stringValue?.data(using: .utf8).flatMap { deserialize($0, decoder) }
}
public override func get(key: String, defaultsStore: DefaultsStore, decoder: JSONDecoder) -> T? {
return nil
}
func deserialize(_ object: Any, _ decoder: JSONDecoder) -> T? {
return (object as? Data).flatMap { try? decoder.decode(T.self, from: $0) }
}
}
/// ConfigBridge for `Codable`
public final class ConfigCodableBridge<T: Codable>: ConfigBridge<T> {
public override func save(key: String, value: T?, defaultsStore: DefaultsStore, encoder: JSONEncoder) {
defaultsStore[key] = try? encoder.encode(value)
}
public override func get(key: String, remoteConfig: RemoteConfig, decoder: JSONDecoder) -> T? {
return deserialize(remoteConfig[key].dataValue, decoder) ??
remoteConfig[key].stringValue?.data(using: .utf8).flatMap{ deserialize($0, decoder) }
}
public override func get(key: String, defaultsStore: DefaultsStore, decoder: JSONDecoder) -> T? {
return defaultsStore[key].flatMap { deserialize($0, decoder)}
}
func deserialize(_ object: Any, _ decoder: JSONDecoder) -> T? {
return (object as? Data).flatMap { try? decoder.decode(T.self, from: $0) }
}
}
/// ConfigBridge for `Array`
public final class ConfigArrayBridge<T: Collection>: ConfigBridge<T> {
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value.flatMap { try? JSONSerialization.data(withJSONObject: $0, options: []) }
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
return deserialize(remoteConfig[key].dataValue) ??
remoteConfig[key].stringValue?.data(using: .utf8).flatMap(deserialize)
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return (defaultsStore[key] as? Data).flatMap(deserialize)
}
func deserialize(_ data: Data) -> T? {
return (try? JSONSerialization.jsonObject(with: data, options: [])).flatMap { $0 as? T }
}
}
/// ConfigBridge for `Array` if `Collection.Element` is `RawRepresentable` (for Enum element).
public final class ConfigRawRepresentableArrayBridge<T: Collection>: ConfigBridge<T> where T.Element: RawRepresentable {
public override func save(key: String, value: T?, defaultsStore: DefaultsStore) {
defaultsStore[key] = value.flatMap { try? JSONSerialization.data(withJSONObject: $0.compactMap { $0.rawValue }, options: []) }
}
public override func get(key: String, remoteConfig: RemoteConfig) -> T? {
let deserialized = deserialize(remoteConfig[key].dataValue) ?? remoteConfig[key].stringValue?.data(using: .utf8).flatMap(deserialize)
return deserialized?.compactMap(T.Element.init(rawValue:)) as? T
}
public override func get(key: String, defaultsStore: DefaultsStore) -> T? {
return (defaultsStore[key] as? Data).flatMap(deserialize).flatMap { $0.compactMap(T.Element.init(rawValue:)) } as? T
}
func deserialize(_ data: Data) -> [T.Element.RawValue]? {
return (try? JSONSerialization.jsonObject(with: data, options: [])).flatMap { $0 as? [T.Element.RawValue] }
}
}
| 36.325203 | 141 | 0.685206 |
89cbb56d76b4aee6d7ae625d577ac4426f207fda | 1,493 | //
// QList_iPhoneUITests.swift
// QList_iPhoneUITests
//
// Created by durban.zhang on 2020/8/23.
// Copyright © 2020 durban.zhang. All rights reserved.
//
import XCTest
class QList_iPhoneUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.931818 | 182 | 0.664434 |
1ddd962fbcb6681190630305abb6e75ee14a501e | 4,056 | //
// CollectionViewController.swift
// FRadioPlayer_ios
//
// Created by Ken Taylor on 25/05/2020.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
import SDWebImage
class CollectionViewController: UIViewController {
let networkStuff = NetworkStuff()
@IBOutlet weak var collectionView: UICollectionView!
var collectionViewFlowLayout: UICollectionViewFlowLayout!
let cellIdentifier = "CustomCollectionViewCell"
var refresher:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
networkStuff.performRequest()
setupCollectionView()
//collectionView.reloadData()
print("reloaded")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupCollectionViewItemZize()
}
private func setupCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
let nib = UINib(nibName: "CustomCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
}
private func setupCollectionViewItemZize() {
if collectionViewFlowLayout == nil {
let numberOfItemPerRow: CGFloat = 4
let lineSpacing: CGFloat = 5
let interItemSpacing: CGFloat = 5
let containerWidth: CGFloat = self.view.bounds.width
let width = (containerWidth - (numberOfItemPerRow+1) * interItemSpacing) / numberOfItemPerRow //- 1
let inset = max(interItemSpacing, floor( (containerWidth - (numberOfItemPerRow*width) - (numberOfItemPerRow-1)*interItemSpacing) / 2 ) )
//let width = (collectionView.frame.width - (numberOfItemPerRow - 1) * interItemSpacing) / numberOfItemPerRow
let height = width
collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: interItemSpacing, left: inset, bottom: interItemSpacing, right: inset)
collectionViewFlowLayout.itemSize = CGSize(width: width, height: height)
collectionViewFlowLayout.sectionInset = .zero
collectionViewFlowLayout.scrollDirection = .vertical
collectionViewFlowLayout.minimumLineSpacing = lineSpacing
collectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing
collectionView.setCollectionViewLayout(collectionViewFlowLayout, animated: true)
}
}
}
extension CollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
NetworkStuff.urlArrayReturnCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CustomCollectionViewCell
cell.imageView?.sd_setImage(with: NetworkStuff.urlArrayReturn[indexPath.row], placeholderImage: #imageLiteral(resourceName: "placeholderImage"), options: .highPriority, completed: nil)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(NetworkStuff.urlArrayReturn[indexPath.row])
let vc = storyboard?.instantiateViewController(identifier: "ImageViewerViewController") as? ImageViewerViewController
PassData.url = NetworkStuff.urlArrayReturn[indexPath.row]
PassData.photoCaption = NetworkStuff.urlArrayReturnTitle[indexPath.row]
//vc.imageView.sd_setImage(with: NetworkStuff.urlArrayReturn[indexPath.row], completed: nil)
self.navigationController?.pushViewController(vc!, animated: true)
}
}
| 36.214286 | 192 | 0.688363 |
1def9215fa3c820e6850a32825de6f51fb4d9575 | 2,518 | //
// LJPageCollectionLayout.swift
// LiveProject
//
// Created by liang on 2017/8/4.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class LJPageCollectionLayout: UICollectionViewLayout {
var sectionInset : UIEdgeInsets = UIEdgeInsets.zero
var itemMargin : CGFloat = 0
var lineMargin : CGFloat = 0
var cols : Int = 4
var rows : Int = 2
fileprivate lazy var maxWidth : CGFloat = 0
fileprivate lazy var attributes : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
}
extension LJPageCollectionLayout {
override func prepare() {
guard let collectionView = collectionView else { return }
let sections = collectionView.numberOfSections
let itemWidth = (collectionView.bounds.size.width - sectionInset.left - sectionInset.right - itemMargin * (CGFloat(cols) - 1)) / CGFloat(cols)
let itemHeight = (collectionView.bounds.size.height - sectionInset.top - sectionInset.bottom - lineMargin * (CGFloat(rows) - 1)) / CGFloat(rows)
var totalPage : Int = 0
for section in 0..<sections {
let items = collectionView.numberOfItems(inSection: section)
for item in 0..<items {
let indexPath = IndexPath(item: item, section: section)
let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
// 在当前section的第几页
let pagesInSection = item / (cols * rows)
// 当前页的第几个
let currentIndex = item % (cols * rows)
let itemX = sectionInset.left + CGFloat(currentIndex % cols) * (itemMargin + itemWidth) + CGFloat(pagesInSection + totalPage) * collectionView.bounds.size.width
let itemY = sectionInset.top + CGFloat(currentIndex / cols) * (lineMargin + itemHeight)
attribute.frame = CGRect(x: itemX, y: itemY, width: itemWidth, height: itemHeight)
attributes.append(attribute)
}
totalPage += (items - 1) / (rows * cols) + 1
}
maxWidth = CGFloat(totalPage) * collectionView.bounds.size.width
}
}
extension LJPageCollectionLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributes
}
}
extension LJPageCollectionLayout {
override var collectionViewContentSize: CGSize {
return CGSize(width: maxWidth, height: 0)
}
}
| 38.738462 | 176 | 0.642971 |
acac8d927d2b659cb668f805d8d385dbfa2e3d02 | 3,048 | //
// VersionStore.swift
//
//
// Created by Balázs Szamódy on 3/7/20.
//
import Foundation
protocol VersionStore {
func getVersion() throws -> String
}
class IOSVersionStore: VersionStore {
func getVersion() throws -> String {
// Get Version from AGVTool
var command = ["xcrun agvtool what-marketing-version"]
var version: [String] = []
guard let v = try Process
.shell(command)
.components(separatedBy: "\"")
.dropFirst().first else {
throw CustomError.versionError
}
version.append(v)
// Get Build from AGVTool
command = ["xcrun agvtool what-version"]
guard let build = try Process.shell(command)
.components(separatedBy: "\n")
.dropFirst()
.first?
.replacingOccurrences(of: " ", with: "") else {
throw CustomError.buildError
}
version.append("(\(build))")
return "# v\(version.joined())\n"
}
}
class AndroidVersionStore: VersionStore {
static let kPackageName = "CW_ANDROID_PACKAGE"
enum AndroidVersionError: LocalizedError {
case packageName
case versionComponents
var errorDescription: String? {
switch self {
case .packageName:
return """
Error: Android Package Name not set.
Set the android package name as `\(AndroidVersionStore.kPackageName)` environment variable.
"""
case .versionComponents:
return "Either versionCode or versionName is not found."
}
}
}
func getVersion() throws -> String {
guard let package = ProcessInfo.processInfo.environment[AndroidVersionStore.kPackageName],
!package.isEmpty else {
throw AndroidVersionError.packageName
}
// "com.sentia.vis.dev"
let commandTemplate = "adb shell dumpsys package \(package) | grep %@"
let commandVariants = ["versionName", "versionCode"]
let output = try commandVariants
.map({
let command = String(format: commandTemplate, $0)
verbosePrint("Command:", command)
return command
})
.map({
try Process.shell([$0])
})
verbosePrint("Output:", output)
let results = output
.compactMap({
$0.split(separator: " ")
.first?
.split(separator: "=")
.last?
.replacingOccurrences(of: "\n", with: "")
})
.map({
String($0)
})
verbosePrint("Version and Build NUmber:", results)
guard results.count == 2 else {
throw AndroidVersionError.versionComponents
}
return "# v\(results[0])(\(results[1]))"
}
}
| 30.178218 | 107 | 0.520997 |
9bacd41893fab2f045cf7e7b6cf37f43bb4a9e4f | 2,848 | //
// Probability.swift
// SwiRL
//
// Created by Maxim Volgin on 05/02/2020.
//
import Foundation
/**
Probability Mass Function (discrete X)
*/
public func PMF(_ x: Double) -> Double { 0.0 } // TODO
/**
Probability Density Function (continuous X)
*/
public func PDF(_ x: Double) -> Double { 0.0 } // TODO
public func odds(probability p: Double) -> Double { p / (1.0 - p) }
public func probability(odds o: Double) -> Double { o / (1.0 + o) }
public func logit(probability p: Double) -> Double { log(odds(probability: p)) }
public func softmax(_ value: Double, _ array: [Double]) -> Double {
guard let max = array.max() else {
return exp(value) / exp(array.reduce(0, +))
}
return exp(value - max) / exp(array.map { $0 - max }.reduce(0, +))
}
public struct Probability {
// MARK: Joint: P(X,Y) = P(X) * P(Y)
/**
P(X,Y) = P(X) * P(Y)
joint = product of marginals
(if independent)
*/
public static func joint(marginals: Double...) -> Double { ∏marginals }
// MARK: Conditional: P(X|Y) = P(X,Y) / P(Y)
/**
P(X|Y) = P(X,Y) / P(Y)
conditional = joint / marginal
= P(X) if independent, i.e. if P(X,Y) = P(X) * P(Y)
*/
public static func conditional(joint xAndY: @autoclosure () -> Double, marginal pY: @autoclosure () -> Double) -> Double {
xAndY() / pY()
}
// MARK: Chain rule: P(X,Y) = P(X|Y) * P(Y) or P(X,Y,Z) = P(X|Y,Z) * P(Y|Z) * P(Z) or P(X₁, ... Xn) = ∏ P(Xᵢ|X₁, ... Xᵢ₋₁)
/**
P(X,Y) = P(X|Y) * P(Y)
P(X,Y,Z) = P(X|Y,Z) * P(Y|Z) * P(Z)
P(X₁, ... Xn) = ∏ P(Xi|X₁, ... Xᵢ₋₁)
joint = conditional * marginal
*/
public static func chain(conditional xGivenY: @autoclosure () -> Double, marginal pY: @autoclosure () -> Double) -> Double {
xGivenY() * pY()
}
/**
p(X) = ∫ p(X,Y) dY
marginal = ∫ joint by y
summation rule
*/
// MARK: On-line Bayes: Pᵢ(Θ) = P(Θ|Xᵢ) = P(Xᵢ|Θ) * Pᵢ₋₁(Θ) / P(Xᵢ)
// MARK: Bayes: P(Θ|X) = P(X|Θ) * P(Θ) / P(X)
/**
P(Θ|X) = P(X|Θ) * P(Θ) / P(X)
Θ - parameter
X - observation
- Parameters:
- likelihood: P(X|Θ)
- prior: P(Θ)
- evidence:P(X)
- Returns: P(Θ|X)
*/
public static func bayes(likelihood xGivenΘ: @autoclosure () -> Double, prior pΘ: @autoclosure () -> Double, evidence pX: @autoclosure () -> Double) -> Double {
xGivenΘ() * pΘ() / pX()
}
/**
P(Θ|X) = P(X,Θ) / P(X)
Θ - parameter
X - observation
- Parameters:
- joint: P(X,Θ)
- evidence:P(X)
- Returns: P(Θ|X)
*/
public static func bayes(joint xAndΘ: @autoclosure () -> Double, evidence pX: @autoclosure () -> Double) -> Double {
xAndΘ() / pX()
}
// MLE: Â = argmaxₐP(X|A)
}
| 26.12844 | 164 | 0.51264 |
48cd10a1b9f5a181886df45f367424239e148bb9 | 511 | //
// SWCollectionViewCell.swift
// SalesManItemCategory
//
// Created by 谢艳 on 2018/11/19.
//
import UIKit
class SWCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
self.nameLabel.textColor = UIColor.swCategoryGreyTextColor()
self.nameLabel.font = UIFont.systemFont(ofSize: 14)
self.nameLabel.numberOfLines = 2
}
public func showContent(title:String){
self.nameLabel.text = title
}
}
| 23.227273 | 68 | 0.686888 |
d5b66d99b8c91e2cc50444be92075796838d5f47 | 2,081 | // MIT License
//
// Copyright (c) 2017 Wesley Wickwire
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public struct EnumMetadata: NominalMetadataType {
public var pointer: UnsafeMutablePointer<EnumMetadataLayout>
public init(pointer: UnsafeMutablePointer<EnumMetadataLayout>) {
self.pointer = pointer
}
public mutating func cases() -> [Case] {
let fieldDescriptor = pointer.pointee.typeDescriptor.pointee
.fieldDescriptor
.advanced()
return (0..<fieldDescriptor.pointee.numFields).map { i in
let record = fieldDescriptor
.pointee
.fields
.element(at: Int(i))
return Case(name: record.pointee.fieldName())
}
}
public mutating func toTypeInfo() -> TypeInfo {
var info = TypeInfo(metadata: self)
info.mangledName = mangledName()
info.cases = cases()
info.genericTypes = genericArguments()
return info
}
}
| 37.160714 | 81 | 0.686209 |
8abf62ef96eccdb0a07ecb54adab272e587373a4 | 27,519 | //
// StringScanner.swift
// StringScanner
//
// Created by Daniele Margutti on 03/12/2016.
// Web: http://www.danielemargutti.com
// Mail: [email protected]
// Twitter: @danielemargutti
// Copyright © 2016 Daniele Margutti. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// Throwable errors of the scanner
///
/// - eof: end of file is reached
/// - invalidInput: invalid input passed to caller function
/// - notFound: failed to match or search value into the scanner's source string
/// - invalidInt: invalid int found, not the expected format
/// - invalidFloat: invalid float found, not the expected format
/// - invalidHEX: invalid HEX found, not the expected format
public enum StringScannerError: Error {
case eof
case notFound
case invalidInput
case invalidInt
case invalidFloat
case invalidHEX
}
/// Bit digits representation for HEX values
public enum BitDigits: Int {
case bit8 = 8
case bit16 = 16
case bit32 = 32
case bit64 = 64
var length: Int {
switch self {
case .bit8: return 2
case .bit16: return 4
case .bit32: return 8
case .bit64: return 16
}
}
}
public class StringScanner {
public typealias SIndex = String.UnicodeScalarView.Index
public typealias SString = String.UnicodeScalarView
//---------------
//MARK: Variables
//---------------
/// Thats the current data of the scanner.
/// Internally it's represented by `String.UnicodeScalarView`
public fileprivate(set) var string: SString
/// Current scanner's index position
public fileprivate(set) var position: SIndex
/// Get the first index of the source string
public var startIndex: SIndex {
return self.string.startIndex
}
/// Get the last index of the source string
public var endIndex: SIndex {
return self.string.endIndex
}
/// Number of scalars consumed up to `position`
/// Since String.UnicodeScalarView.Index is not a RandomAccessIndex,
/// this makes determining the position *much* easier)
public fileprivate(set) var consumed: Int
/// Return true if scanner reached the end of the string
public var isAtEnd: Bool {
return (self.position == string.endIndex)
}
/// Returns the content of scanner's string from current value of the position till the end
/// `position` its not updated by the operation.
///
/// - Returns: remainder string till the end of source's data
public var remainder: String {
var remString: String = ""
var idx = self.position
while idx != self.string.endIndex {
remString.unicodeScalars.append(self.string[idx])
idx = self.string.index(after:idx)
}
return remString
}
//-----------------
//MARK: Init
//-----------------
/// Initialize a new scanner instance from given source string
///
/// - Parameter string: source string
public init(_ string: String) {
self.string = string.unicodeScalars
self.position = self.string.startIndex
self.consumed = 0
}
//-----------------
//MARK: Scan Values
//-----------------
/// If the current scanner position is not at eof return the next scalar at position and move `position` to the next index
/// Otherwise it throws with .eof and `position` is not updated.
///
/// - Returns: the next scalar
/// - Throws: throw .eof if reached
@discardableResult
public func scanChar() throws -> UnicodeScalar {
guard self.position != self.string.endIndex else {
throw StringScannerError.eof
}
let char = self.string[self.position]
self.position = self.string.index(after: self.position)
self.consumed += 1
return char
}
/// Scan the next integer value after the current scalar position; consume scalars from {0..9} until a non numeric
/// value is encountered. Return the integer representation in base 10.
/// `position` index is advanced to the end of the number.
/// Throws .invalidInt if scalar at the current `position` is not in the range `"0"` to `"9"`
///
/// - Returns: read integer in base 10
/// - Throws: throw .invalidInt if non numeric value is encountered
public func scanInt() throws -> Int {
var parsedInt = 0
try self.session(peek: true, accumulate: false, block: { i,c in
while i != self.string.endIndex && self.string[i] >= "0" && self.string[i] <= "9" {
parsedInt = parsedInt * 10 + Int(self.string[i].value - UnicodeScalar("0").value )
i = self.string.index(after: i)
c += 1
}
if i == self.position {
throw StringScannerError.invalidInt
}
// okay valid, store changes to index
self.position = i
self.consumed = c
})
return parsedInt
}
/// Scan for float value (xx.xx) and convert it into Float.
/// Return the float representation in base 10.
/// `position` index is advanced to the end of the number only if conversion works, otherwise it will be not updated and
/// .invalidFloat is thrown.
///
/// - Returns: parsed float value
/// - Throws: throw an exception .invalidFloat or .eof according to the error
public func scanFloat() throws -> Float {
let prevConsumed = self.consumed
func throwAndBackBy(length: Int) {
self.position = self.string.index(self.position, offsetBy: -length)
self.consumed -= length
}
guard let strValue = try self.scan(untilIn: CharacterSet(charactersIn: "-+0123456789.")) else {
throw StringScannerError.invalidFloat
}
guard let value = Float(strValue) else {
throw StringScannerError.invalidFloat
}
return value
}
/// Scan an HEX digit expressed as 0x/0X<number> or #<number> where number is the value expressed with according bit number
/// If scan succeded it return parsed value and `position` is updated at the end of the value.
/// If scan fail function throws and no values are updated
///
/// - Parameter digits: type of digits to parse (8,16,32 or 64 bits)
/// - Returns: the int value in base 10 converted from HEX base
/// - Throws: throw .hexExpected if value is not expressed in HEX string according to specified digits
public func scanHexInt(_ digits: BitDigits = .bit16) throws -> Int {
func parseHexInt(_ digits: BitDigits, _ consumed: inout Int) throws -> Int {
let strValue = try self.scan(length: digits.length)
consumed += digits.length
guard let parsedInt = Int(strValue, radix: 16) else {
throw StringScannerError.invalidHEX
}
return parsedInt
}
var value: Int = 0
var consumed: Int = 0
if self.string[self.position] == "#" { // the format start with #, numbers is following
try self.move(1, accumulate: false)
consumed += 1 // move on to digits and parse them
value = try parseHexInt(digits, &consumed)
} else {
do {
let prefix = try self.scan(length: 2).uppercased()
consumed += 2
guard prefix == "0X" else { // hex is in 0x or 0X format followed by values
throw StringScannerError.invalidHEX
}
value = try parseHexInt(digits, &consumed)
} catch {
// something went wrong and value cannot be parsed,
// go back with the `position` index and throw an errro
try! self.back(length: consumed)
throw StringScannerError.invalidHEX
}
}
return value
}
/// Scan until given character is found starting from current scanner `position` till the end of the source string.
/// Scanner's `position` is updated only if character is found and set just before it.
/// Throw an exception if .eof is reached or .notFound if char was not found (in this case scanner's position is not updated)
///
/// - Parameter char: scalar to search
/// - Returns: the string until the character (excluded)
/// - Throws: throw an exception on .eof or .notFound
public func scan(upTo char: UnicodeScalar) throws -> String? {
return try self.move(peek: false, upTo: char).string
}
/// Scan until given character's is found.
/// Index is reported before the start of the sequence, scanner's `position` is updated only if sequence is found.
/// Throw an exception if .eof is reached or .notFound if sequence was not found
///
/// - Parameter charSet: character set to search
/// - Returns: found index
/// - Throws: throw .eof or .notFound
public func scan(upTo charSet: CharacterSet) throws -> String? {
return try self.move(peek: false, accumulate: true, upToCharSet: charSet).string
}
/// Scan until the next character of the scanner is contained into given character set
/// Scanner's position is updated automatically at the end of the sequence if validated, otherwise it will not touched.
///
/// - Parameter charSet: chracters set
/// - Returns: the string accumulated scanning until chars set is evaluated
/// - Throws: throw .eof or .notFound
public func scan(untilIn charSet: CharacterSet) throws -> String? {
return try self.move(peek: false, accumulate: true, untilIn: charSet).string
}
/// Scan until specified string is encountered and update indexes if found
/// Throw an exception if .eof is reached or string is not found
///
/// - Parameter string: string to search
/// - Returns: string up to search string (excluded)
/// - Throws: throw .eof or .notFound
@discardableResult
public func scan(upTo string: String) throws -> String? {
return try self.move(peek: false, upTo: string).string
}
/// Scan and consume at the scalar starting from current position, testing it with function test.
/// If test returns `true`, the `position` increased. If `false`, the function returns.
///
/// - Parameter test: test to pass
/// - Returns: accumulated string
@discardableResult
public func scan(untilTrue test: ((UnicodeScalar) -> (Bool)) ) -> String {
return self.move(peek: false, accumulate: true, untilTrue: test).string ?? ""
}
/// Read next length characters and accumulate it
/// If operation is succeded scanner's `position` are updated according to consumed scalars.
/// If fails an exception is thrown and `position` is not updated
///
/// - Parameter length: number of scalar to ad
/// - Returns: captured string
/// - Throws: throw an .eof exception
@discardableResult
public func scan(length: Int = 1) throws -> String {
return try self.move(length, accumulate: true).string!
}
//-----------------
//MARK: Peek Values
//-----------------
/// Peek until chracter is found starting from current scanner's `position`.
/// Scanner's position is never updated.
/// Throw an exception if .eof is reached or .notFound if char was not found.
///
/// - Parameter char: scalar to search
/// - Returns: the index found
/// - Throws: throw an exception on .eof or .notFound
public func peek(upTo char: UnicodeScalar) throws -> SIndex {
return try self.move(peek: true, upTo: char).index
}
/// Peek until one the characters specified by set is encountered
/// Index is reported before the start of the sequence, but scanner's `position` is never updated.
/// Throw an exception if .eof is reached or .notFound if sequence was not found
///
/// - Parameter charSet: scalar set to search
/// - Returns: found index
/// - Throws: throw .eof or .notFound
public func peek(upTo charSet: CharacterSet) throws -> SIndex {
return try self.move(peek: true, accumulate: false, upToCharSet: charSet).index
}
/// Peek until the next character of the scanner is contained into given.
/// Scanner's `position` is never updated.
///
/// - Parameter charSet: characters set to evaluate
/// - Returns: the index at the end of the sequence
/// - Throws: throw .eof or .notFound
public func peek(untilIn charSet: CharacterSet) throws -> SIndex {
let (endIndex,_) = try self.move(peek: true, accumulate: false, untilIn: charSet)
return endIndex
}
/// Iterate until specified string is encountered without updating indexes.
/// Scanner's `position` is never updated but it's reported the index just before found occourence.
///
/// - Parameter string: string to search
/// - Returns: index where found string was found
/// - Throws: throw .eof or .notFound
public func peek(upTo string: String) throws -> SIndex {
return try self.move(peek: true, upTo: string).index
}
/// Peeks at the scalar at the current position, testing it with function test.
/// It only peeks so current scanner's `position` is not increased at the end of the operation
///
/// - Parameter test: test to pass
public func peek(untilTrue test: ((UnicodeScalar) -> (Bool)) ) -> SIndex {
return self.move(peek: true, accumulate: false, untilTrue: test).index
}
//-----------
//MARK: Match
//-----------
/// Throw if the scalar at the current position don't match given scalar.
/// Advance scanner's `position` to the end of the match.
///
/// - Parameter char: scalar to match
/// - Throws: throw if does not match or index reaches eof
@discardableResult
public func match(_ char: UnicodeScalar) -> Bool {
guard self.position != self.string.endIndex else {
return false
}
if self.string[self.position] != char {
return false
}
// Advance by one scalar, the one we matched
self.position = self.string.index(after: self.position)
self.consumed += 1
return true
}
/// Throw if scalars starting at the current position don't match scalars in given string.
/// Advance scanner's `position` to the end of the match string.
///
/// - Parameter string: string to match
/// - Throws: throw if does not match or index reaches eof
public func match(_ match: String) -> Bool {
var result: Bool = true
try! self.session(peek: false, accumulate: false, block: { i,c in
for char in match.unicodeScalars {
if i == self.string.endIndex {
result = false
break
}
if self.string[i] != char {
result = false
break
}
i = self.string.index(after: i)
c += 1
}
})
return result
}
//------------
//MARK: Others
//------------
/// Move scanner's `position` to the start of the string
public func reset() {
self.position = self.string.startIndex
self.consumed = 0
}
/// Move to the index's end index
public func peekAtEnd() {
self.position = self.string.endIndex
let distance = self.string.distance(from: self.string.startIndex, to: self.position)
self.consumed = distance
}
/// Attempt to advance scanner's by length
/// If operation is not possible (reached the end of the string) it throws and current scanner's `position` of the index did not change
/// If operation succeded scanner's `position` is updated.
///
/// - Parameter length: length to advance
/// - Throws: throw if .eof
public func skip(length: Int = 1) throws {
try self.move(length, accumulate: false)
}
/// Attempt to advance scanner past all characters in the provided
/// character set.
/// If the operation is not possible (reached the end of the string),
/// it throws and current scanner's `position` of the index did not change
/// If operation succeded, the scanner's `position` is updated.
///
/// - Parameter characterSet: The set of characters to skip.
/// - Throws: throw if .eof
public func skip(charactersIn characterSet: CharacterSet) throws {
_ = try self.move(peek: false, accumulate: false, whileIn: characterSet)
}
/// Attempt to advance the position back by length
/// If operation fails scanner's `position` is not touched
/// If operation succeded scaner's`position` is modified according to new value
///
/// - Parameter length: length to move
/// - Throws: throw if .eof
public func back(length: Int = 1) throws {
guard length <= self.consumed else { // more than we can go back
throw StringScannerError.invalidInput
}
if length == 1 {
self.position = self.string.index(self.position, offsetBy: -1)
self.consumed -= 1
return
}
var l = length
while l > 0 {
self.position = self.string.index(self.position, offsetBy: -1)
self.consumed -= 1
l -= 1
}
}
//--------------------
//MARK: Private Funcs
//--------------------
@discardableResult
private func move(_ length: Int = 1, accumulate: Bool) throws -> (index: SIndex, string: String?) {
if length == 1 && self.position != self.string.endIndex {
// Special case if proposed length is a single character
self.position = self.string.index(after: self.position)
self.consumed += 1
return (self.position, String(self.string[self.string.index(before: self.position)]))
}
// Use temporary indexes and don't touch the real ones until we are
// sure the operation succeded
var proposedIdx = self.position
var initialPosition = self.position
var proposedConsumed = 0
var remaining = length
while remaining > 0 {
if proposedIdx == self.string.endIndex {
throw StringScannerError.eof
}
proposedIdx = self.string.index(after: proposedIdx)
proposedConsumed += 1
remaining -= 1
}
var result: String? = nil
if accumulate == true { // if user need accumulate string we want to provide it
result = ""
result!.reserveCapacity( (proposedConsumed - self.consumed) ) // just an optimization
while initialPosition != proposedIdx {
result!.unicodeScalars.append(self.string[initialPosition])
initialPosition = self.string.index(after: initialPosition)
}
}
// Write changes only if skip operation succeded
self.position = proposedIdx
self.consumed = proposedConsumed
return (self.position,result)
}
/// Move the index until scalar at given index is part of passed char set, then return the index til it and accumulated string (if requested)
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - accumulate: accumulate return a valid string in output sum of the scan operation
/// - charSet: character set target of the operation
/// - Returns: index and content of the string
/// - Throws: throw .notFound if string is not found or .eof if end of file is reached
private func move(peek: Bool, accumulate: Bool, untilIn charSet: CharacterSet) throws -> (index: SIndex, string: String?) {
if charSet.contains(self.string[self.position]) == false { // ops
throw StringScannerError.notFound
}
return try self.session(peek: peek, accumulate: accumulate, block: { i,c in
while i != self.string.endIndex && charSet.contains(self.string[i]) {
i = self.string.index(after: i)
c += 1
}
})
}
/// Move the index while scalar at current index is part of passed char set,
/// then return the index after it and the accumulated string (if requested)
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - accumulate: accumulate return a valid string in output sum of the scan operation
/// - charSet: character set target of the operation
/// - Returns: index and content of the string
/// - Throws: throw .notFound if string is not found or .eof if end of file is reached
private func move(peek: Bool, accumulate: Bool,
whileIn charSet: CharacterSet) throws -> (index: SIndex, string: String?) {
return try self.session(peek: peek, accumulate: accumulate, block: { i,c in
while i != self.string.endIndex && charSet.contains(self.string[i]) {
i = self.string.index(after: i)
c += 1
}
})
}
/// Move up to passed scalar is found
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - char: given scalar to search
/// - Returns: index til found character and accumulated string
/// - Throws: throw .notFound or .eof
@discardableResult
private func move(peek: Bool, upTo char: UnicodeScalar) throws -> (index: SIndex, string: String?) {
return try self.session(peek: peek, accumulate: true, block: { i,c in
// continue moving forward until we reach the end of scanner's string
// or current character at scanner's string current position differs from we are searching for
while i != self.string.endIndex && self.string[i] != char {
i = self.string.index(after: i)
c += 1
}
})
}
/// Move next scalar until a character specified in character set is found and return the index and accumulated string (if requested)
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - accumulate: true to get accumulated string til found index
/// - charSet: character set target of the operation
/// - Returns: index and accumulated string
/// - Throws: throw .eof or .notFound
@discardableResult
private func move(peek: Bool, accumulate: Bool, upToCharSet charSet: CharacterSet) throws -> (index: SIndex, string: String?) {
return try self.session(peek: peek, accumulate: accumulate, block: { i,c in
// continue moving forward until we reach the end of scanner's string
// or current character at scanner's string current position differs from we are searching for
while i != self.string.endIndex && charSet.contains(self.string[i]) == false {
i = self.string.index(after: i)
c += 1
}
})
}
/// Move next scalar until specified test for current scalar return true, then get the index and accumulated string
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - accumulate: true to get accumulated string until test return true
/// - test: test
/// - Returns: throw .eof or .notFound
@discardableResult
private func move(peek: Bool, accumulate: Bool, untilTrue test: ((UnicodeScalar) -> (Bool)) ) -> (index: SIndex, string: String?) {
return try! self.session(peek: peek, accumulate: accumulate, block: { i,c in
while i != self.string.endIndex {
if test(self.string[i]) == false { // test is not passed, we return
return
}
i = self.string.index(after: i)
c += 1
}
})
}
/// Move next scalar until specified string is found, then get the index and accumulated string
///
/// - Parameters:
/// - peek: peek to perform a non destructive operation to scanner's `position`
/// - string: string to search
/// - Returns: index and string
/// - Throws: throw .eof or .notFound
@discardableResult
private func move(peek: Bool, upTo string: String) throws -> (index: SIndex, string: String?) {
let search = string.unicodeScalars
guard let firstSearchChar = search.first else { // Invalid search string
throw StringScannerError.invalidInput
}
if search.count == 1 { // If we are searching for a single char we want to forward call to the specific func
return try self.move(peek: peek, upTo: firstSearchChar)
}
return try self.session(peek: peek, accumulate: true, block: { i,c in
let remainderSearch = search[search.index(after: search.startIndex)..<search.endIndex]
let endStringIndex = self.string.endIndex
// Candidates allows us to store the position of index for any candidate string
// A candidate session happens when we found the first char of search string (firstSearchChar)
// into our scanner string.
// We will use these indexes to switch back position of the scanner if the entire searchString will found
// in order to exclude searchString itself from resulting string/indexes
var candidateStartIndex = i
var candidateConsumed = c
mainLoop : while i != endStringIndex {
// Iterate all over the strings searching for first occourence of the first char of the string to search
while self.string[i] != firstSearchChar {
i = self.string.index(after: i) // move to the next item
c += 1 // increment consumed chars
if i == endStringIndex { // we have reached the end of the scanner's string
throw StringScannerError.eof
}
}
// Okay we have found first char of our search string into our data
// First of all we store in proposedIndex and proposedConsumed the position were we have found
// this candidate. If validated we adjust back the indexes in of c,i in order to exclude found string itself
candidateStartIndex = i
candidateConsumed = c
// We need to validate the remaining characters and see if are the same
i = self.string.index(after: i) // scan from second character of the search string
c += 1 // (clearly also increments consumed chars)
// now we want to compare the reamining chars of the search (remainderSearch) with the
// next chars of our current position in scanner's string
for searchCChar in remainderSearch {
if i == endStringIndex { // we have reached the end of the scanner's string
throw StringScannerError.eof
}
if self.string[i] != searchCChar {
continue mainLoop
}
// Go the next char
i = self.string.index(after: i)
c += 1
}
// Wow the string is that!
// Adjust back the indexes
i = candidateStartIndex
c = candidateConsumed
break
}
})
}
/// Initiate a scan or peek session. This func allows you to keep changes in index and consumed
/// chars; moreover it returns the string accumulated during the move session.
///
/// - Parameters:
/// - peek: if true it will update both consumed and position indexes of the scanner at the end with sPosition and sConsumed values
/// - accumulate: true to return the string from initial position till the end of reached index
/// - block: block with the operation to execute
/// - Returns: return the new proposed position for scanner's index and accumulated string
/// - Throws: throw if block throws
@discardableResult
private func session(peek: Bool, accumulate: Bool = true,
block: (_ sPosition: inout SIndex, _ sConsumed: inout Int) throws -> (Void) )
throws -> (index: SIndex, string: String?) {
// Keep in track with status of the position and consumed indexes before anything change
var initialPosition = self.position
let initialConsumed = self.consumed
var sessionPosition = self.position
var sessionConsumed = 0
// execute the real code into block
try block(&sessionPosition,&sessionConsumed)
var result: String? = ""
if sessionConsumed == 0 {
return (sessionPosition, result)
}
if accumulate == true {
result = ""
result!.reserveCapacity( (sessionConsumed - initialConsumed) ) // just an optimization
while initialPosition != sessionPosition {
result!.unicodeScalars.append(self.string[initialPosition])
initialPosition = self.string.index(after: initialPosition)
}
}
if peek == false { // Write changes to the main scanner's indexes
self.position = sessionPosition
self.consumed += sessionConsumed
}
return (sessionPosition,result)
}
}
| 37.339213 | 142 | 0.694102 |
9b04016ead22b1a1cd98a73dbf09de6ec3b4e9b7 | 7,177 | //
// Xcore
// Copyright © 2016 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
extension Theme {
private static var didSet = false
/// A method to set light and dark theme.
///
/// - Note: This method can only be called once. Any subsequent calls will be
/// ignored.
///
/// - Parameters:
/// - light: The nonadaptable light theme for the interface.
/// - dark: The nonadaptable dark theme for the interface.
/// - current: The current theme. The default value is `.light`.
/// - Returns: `true` if first call; otherwise, `false`.
@discardableResult
public static func set(light: Theme, dark: Theme, current: Theme? = nil) -> Bool {
guard !didSet else {
return false
}
didSet = true
self.light = light
self.dark = dark
self.current = current ?? light
setSystemComponentsTheme()
setNavigationBarBackButtonTheme()
setSearchBarTheme()
setDynamicTableViewTheme()
setComponentsTheme()
return true
}
private static func setSystemComponentsTheme() {
UIColor.appTint = current.tintColor
UIColor.appSeparator = current.separatorColor
UIApplication.sharedOrNil?.delegate?.window??.tintColor = current.tintColor
UIBarButtonItem.appearance().setTitleTextAttributes(UIViewController.defaultNavigationBarTextAttributes, for: .normal)
UINavigationBar.appearance().apply {
$0.titleTextAttributes = UIViewController.defaultNavigationBarTextAttributes
$0.tintColor = current.tintColor
$0.barTintColor = .white
$0.barStyle = .black
$0.isTranslucent = true
}
UIToolbar.appearance().apply {
$0.tintColor = current.tintColor
$0.barTintColor = .white
$0.barStyle = .black
$0.isTranslucent = true
}
UIPageControl.appearance().apply {
$0.pageIndicatorTintColor = current.tintColor
$0.currentPageIndicatorTintColor = current.toggleColor
$0.backgroundColor = .clear
}
UISwitch.appearance().apply {
$0.tintColor = current.textColor.alpha(0.08)
$0.onTintColor = current.toggleColor
}
UISlider.appearance().apply {
$0.maximumTrackTintColor = current.textColor.alpha(0.16)
}
UITabBar.appearance().apply {
$0.tintColor = current.tintColor
$0.borderColor = current.separatorColor
$0.borderWidth = .onePixel
}
}
private static func setNavigationBarBackButtonTheme() {
UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).apply {
$0.backIndicatorImage = UIImage(assetIdentifier: .navigationBarBackArrow)
$0.backIndicatorTransitionMaskImage = UIImage(assetIdentifier: .navigationBarBackArrow)
}
UIBarButtonItem.appearance(whenContainedInInstancesOf: [NavigationController.self])
.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .default)
}
private static func setSearchBarTheme() {
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).apply {
// SearchBar Cancel button normal state
$0.setTitleTextAttributes([
.foregroundColor: current.tintColor,
.font: UIFont.app(style: .body)
], for: .normal)
// SearchBar Cancel button disabled state
$0.setTitleTextAttributes([
.foregroundColor: current.tintColor.alpha(0.5)
], for: .disabled)
}
// SearchBar text attributes
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [
.foregroundColor: current.textColor,
.font: UIFont.app(style: .body)
]
UISearchBar.appearance().placeholderTextColor = current.textColor.alpha(0.5)
}
private static func setDynamicTableViewTheme() {
// MARK: DynamicTableView
DynamicTableView.appearance().apply {
$0.headerFont = .app(style: .caption1)
$0.headerTextColor = current.textColor
$0.footerFont = .app(style: .caption1)
$0.footerTextColor = current.textColorSecondary
$0.accessoryFont = .app(style: .subheadline)
$0.accessoryTextColor = current.textColorSecondary
$0.accessoryTintColor = current.tintColor
$0.checkboxOffTintColor = current.separatorColor
$0.separatorColor = current.separatorColor
$0.rowActionDeleteColor = .appleRed
$0.isEmptyCellsHidden = true
}
DynamicTableViewCell.appearance().apply {
$0.titleTextColor = current.textColor
$0.subtitleTextColor = current.textColorSecondary
$0.contentInset = UIEdgeInsets(top: 9, left: 15, bottom: 10, right: 15)
$0.textImageSpacing = .defaultPadding
}
IconLabelView.appearance().apply {
$0.titleTextColor = current.textColor
$0.subtitleTextColor = current.textColorSecondary
}
BlurView.appearance().blurOpacity = 0.8
}
private static func setComponentsTheme() {
SeparatorView.appearance().tintColor = current.separatorColor
#if canImport(Haring)
MarkupText.appearance.apply {
$0.textColor = current.textColor
}
#endif
UIViewController.defaultAppearance.apply {
$0.tintColor = current.tintColor
$0.prefersTabBarHidden = true
}
UIButton.defaultAppearance.apply {
$0.configuration = .callout
$0.height = AppConstants.uiControlsHeight
$0.isHeightSetAutomatically = true
$0.highlightedAnimation = .scale
$0.configurationAttributes.apply {
// Styles Updates
$0[.base].font = .app(style: .body)
$0[.base].textColor = current.buttonTextColor
$0[.base].tintColor = current.tintColor
$0[.callout].textColor = .white
$0[.callout].backgroundColor = current.buttonBackgroundColor
$0[.calloutSecondary].backgroundColor = current.buttonBackgroundColorSecondary
$0[.pill].backgroundColor = current.buttonBackgroundColorPill
// Toggle Styles
$0[.checkbox].font = .app(style: .caption2)
$0[.checkbox].tintColor = current.toggleColor
$0[.radioButton].tintColor = current.toggleColor
}
}
LabelTextView.appearance().apply {
$0.linkTextAttributes = [.foregroundColor: current.linkColor]
$0.textColor = current.textColor
$0.font = .app(style: .body)
}
Picker.RowView.appearance().apply {
$0.titleTextColor = current.textColor
$0.subtitleTextColor = current.textColorSecondary
}
}
}
| 36.065327 | 126 | 0.615578 |
5bcd146feb7925d88734b01ae331dd0706aa8288 | 11,298 | // swiftlint:disable all
// NSViewExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
// MARK: - Properties
public extension NSView {
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
@IBInspectable
var borderColor: NSColor? {
get {
guard let color = layer?.borderColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.borderColor = newValue?.cgColor
}
}
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
@IBInspectable
var borderWidth: CGFloat {
get {
return layer?.borderWidth ?? 0
}
set {
wantsLayer = true
layer?.borderWidth = newValue
}
}
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer?.cornerRadius ?? 0
}
set {
wantsLayer = true
layer?.masksToBounds = true
layer?.cornerRadius = newValue.magnitude
}
}
func roundCorners(_ corners: CACornerMask, radius: CGFloat) {
wantsLayer = true
layer?.cornerRadius = radius
layer?.maskedCorners = corners
}
// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
@IBInspectable
var shadowColor: NSColor? {
get {
guard let color = layer?.shadowColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.shadowColor = newValue?.cgColor
}
}
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
@IBInspectable
var shadowOffset: CGSize {
get {
return layer?.shadowOffset ?? CGSize.zero
}
set {
wantsLayer = true
layer?.shadowOffset = newValue
}
}
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
@IBInspectable
var shadowOpacity: Float {
get {
return layer?.shadowOpacity ?? 0
}
set {
wantsLayer = true
layer?.shadowOpacity = newValue
}
}
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer?.shadowRadius ?? 0
}
set {
wantsLayer = true
layer?.shadowRadius = newValue
}
}
/// SwifterSwift: Background color of the view; also inspectable from Storyboard.
@IBInspectable
var layerBackgroundColor: NSColor? {
get {
if let colorRef = layer?.backgroundColor {
return NSColor(cgColor: colorRef)
} else {
return nil
}
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
var center: CGPoint {
set {
let rect = CGRect(origin: CGPoint(x: newValue.x - frame.width / 2.0, y: newValue.y - frame.height / 2.0), size: frame.size)
frame = rect
}
get {
CGPoint(x: frame.origin.x + frame.width / 2.0, y: frame.origin.y + frame.height / 2.0)
}
}
}
// MARK: - Methods
public extension NSView {
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
// func addSubviews(_ subviews: [NSView]) {
// subviews.forEach { addSubview($0) }
// }
/// SwifterSwift: Remove all subviews in view.
func removeSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
func imageRepresentation(size: CGSize? = nil) -> NSImage?{
let imageSize = size ?? self.size
let rect = CGRect(origin: .zero, size: imageSize)
guard let bit = bitmapImageRepForCachingDisplay(in: rect) else { return nil }
bit.size = imageSize
cacheDisplay(in: rect, to: bit)
let image = NSImage(size: imageSize)
image.addRepresentation(bit)
return image
}
}
#endif
private var AssociatedObjectHandle: UInt8 = 0
// MARK: - MMLayout
extension NSView {
private struct AssociatedKeys {
static var mm = "mm"
}
var mm: FrameViewDSL {
get {
var mm = objc_getAssociatedObject(self, &AssociatedKeys.mm) as? FrameViewDSL
if mm == nil {
mm = FrameViewDSL(view: self)
objc_setAssociatedObject(self, &AssociatedKeys.mm, mm, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return mm!
}
}
}
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
import ObjectiveC.runtime
#if os(iOS) || os(tvOS)
public typealias FrameView = UIView
public typealias EdgeInsets = UIEdgeInsets
#else
public typealias FrameView = NSView
public typealias EdgeInsets = NSEdgeInsets
#endif
class FrameViewDSL {
internal let view: FrameView
init(view: FrameView) {
self.view = view
}
var x: CGFloat {
get {
return view.frame.origin.x
}
set {
var frame = view.frame
frame.origin.x = newValue
view.frame = frame
}
}
var y: CGFloat {
get {
return view.frame.origin.y
}
set {
var frame = view.frame
frame.origin.y = newValue
view.frame = frame
}
}
var width: CGFloat {
get {
return view.frame.width
}
set {
var frame = view.frame
frame.size.width = newValue
view.frame = frame
}
}
var height: CGFloat {
get {
return view.frame.height
}
set {
var frame = view.frame
frame.size.height = newValue
view.frame = frame
}
}
var size: CGSize {
get {
return view.frame.size
}
set {
var frame = view.frame
frame.size = newValue
view.frame = frame
}
}
var centerX: CGFloat {
get {
return view.center.x
}
set {
var center = view.center
center.x = newValue
view.center = center
}
}
var centerY: CGFloat {
get {
return view.center.y
}
set {
var center = view.center
center.y = newValue
view.center = center
}
}
var maxX: CGFloat {
return view.frame.maxX
}
var minX: CGFloat {
return view.frame.minX
}
var maxY: CGFloat {
return view.frame.maxY
}
var minY: CGFloat {
return view.frame.minY
}
var top: CGFloat {
get {
return y
}
set {
y = newValue
}
}
var left: CGFloat {
get {
return x
}
set {
x = newValue
}
}
var right: CGFloat {
get {
assert(view.superview != nil, "must add subview first")
return view.superview!.mm.width - view.mm.maxX
}
set {
view.mm.x += view.mm.right - newValue
}
}
var bottom: CGFloat {
get {
assert(view.superview != nil, "must add subview first")
return view.superview!.mm.height - view.mm.maxY
}
set {
view.mm.y += view.mm.bottom - newValue
}
}
// MARK: - chain
@discardableResult
func top(_ value: CGFloat) -> Self {
view.mm.y = value
return self
}
@discardableResult
func bottom(_ value: CGFloat) -> Self {
view.mm.bottom = value
return self
}
@discardableResult
func flexToBottom(_ value: CGFloat) -> Self {
view.mm.height += view.mm.bottom - value
return self
}
@discardableResult
func left(_ value: CGFloat) -> Self {
view.mm.x = value
return self
}
@discardableResult
func right(_ value: CGFloat) -> Self {
view.mm.right = value
return self
}
@discardableResult
func flexToRight(_ value: CGFloat) -> Self {
view.mm.width += view.mm.right - value
return self
}
@discardableResult
func width(_ value: CGFloat) -> Self {
view.mm.width = value
return self
}
@discardableResult
func height(_ value: CGFloat) -> Self {
view.mm.height = value
return self
}
@discardableResult
func size(_ value: CGSize) -> Self {
view.mm.size = value
return self
}
@discardableResult
func centerX(_ value: CGFloat) -> Self {
view.mm.centerX = value
return self
}
@discardableResult
func centerY(_ value: CGFloat) -> Self {
view.mm.centerY = value
return self
}
@discardableResult
func center() -> Self {
if let superView = view.superview {
view.mm.centerX = superView.mm.width / 2.0
view.mm.centerY = superView.mm.height / 2.0
}
return self
}
@discardableResult
func fill(inset: EdgeInsets) -> Self {
if let superView = view.superview {
view.mm.x = 0 + inset.left
view.mm.y = 0 + inset.top
view.mm.width = superView.mm.width - inset.left - inset.right
view.mm.height = superView.mm.height - inset.top - inset.bottom
}
return self
}
}
protocol NibLoadable {
// Name of the nib file
static var nibName: String { get }
static func createFromNib(in bundle: Bundle) -> Self
}
extension NibLoadable where Self: NSView {
// Default nib name must be same as class name
static var nibName: String {
return String(describing: Self.self)
}
static func createFromNib(in bundle: Bundle = Bundle.main) -> Self {
var topLevelArray: NSArray?
bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
let views = [Any](topLevelArray!).filter { $0 is Self }
return views.last as! Self
}
}
| 23.936441 | 135 | 0.531421 |
db519841a38f6db25410163fe6f5d151e9d6773e | 945 | //
// SocialFrameworkTwitterTests.swift
// SocialFrameworkTwitterTests
//
// Created by Carlos Butron on 03/12/14.
// Copyright (c) 2014 Carlos Butron. All rights reserved.
//
import UIKit
import XCTest
class SocialFrameworkTwitterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.540541 | 111 | 0.631746 |
910dde9d2a2843de78f0826be2c81f2d8d134ff7 | 4,107 | // Copyright SIX DAY LLC. All rights reserved.
import UIKit
class TokenHeaderView: UIView {
lazy var amountLabel: UILabel = {
let label = UILabel(frame: .zero)
label.textColor = Colors.black
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var fiatAmountLabel: UILabel = {
let label = UILabel(frame: .zero)
label.textColor = Colors.black
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var imageView: TokenImageView = {
let imageView = TokenImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy var buttonsView: TransactionsFooterView = {
let footerView = TransactionsFooterView(
frame: .zero,
bottomOffset: 5
)
footerView.translatesAutoresizingMaskIntoConstraints = false
footerView.setBottomBorder()
return footerView
}()
lazy var container: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 0
stackView.distribution = .equalSpacing
stackView.alignment = .center
return stackView
}()
// let currencyAmountLabel = UILabel()
let percentChange = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
fiatAmountLabel.translatesAutoresizingMaskIntoConstraints = false
fiatAmountLabel.textAlignment = .right
amountLabel.translatesAutoresizingMaskIntoConstraints = false
amountLabel.textAlignment = .right
// currencyAmountLabel.translatesAutoresizingMaskIntoConstraints = false
// currencyAmountLabel.textAlignment = .right
//
percentChange.translatesAutoresizingMaskIntoConstraints = false
percentChange.textAlignment = .right
let amountStack = UIStackView(arrangedSubviews: [amountLabel])
amountStack.translatesAutoresizingMaskIntoConstraints = false
amountStack.axis = .horizontal
amountStack.spacing = 5
let marketPriceStack = UIStackView(arrangedSubviews: [fiatAmountLabel, percentChange])
marketPriceStack.translatesAutoresizingMaskIntoConstraints = false
marketPriceStack.axis = .horizontal
marketPriceStack.spacing = 5
//
// let rightStackView = UIStackView(arrangedSubviews: [marketPriceStack])
// rightStackView.translatesAutoresizingMaskIntoConstraints = false
// rightStackView.axis = .vertical
// rightStackView.alignment = .center
// rightStackView.spacing = 5
container.addArrangedSubview(.spacer(height: StyleLayout.sideMargin * 2))
container.addArrangedSubview(imageView)
container.addArrangedSubview(.spacer(height: 12))
container.addArrangedSubview(amountLabel)
container.addArrangedSubview(marketPriceStack)
container.addArrangedSubview(.spacer(height: 10))
container.addArrangedSubview(buttonsView)
addSubview(container)
NSLayoutConstraint.activate([
container.topAnchor.constraint(equalTo: topAnchor),
container.leadingAnchor.constraint(equalTo: leadingAnchor),
container.trailingAnchor.constraint(equalTo: trailingAnchor),
container.bottomAnchor.constraint(equalTo: bottomAnchor),
buttonsView.leadingAnchor.constraint(equalTo: leadingAnchor),
buttonsView.trailingAnchor.constraint(equalTo: trailingAnchor),
imageView.heightAnchor.constraint(equalToConstant: 84),
imageView.widthAnchor.constraint(equalToConstant: 84),
])
backgroundColor = Colors.veryVeryLightGray
buttonsView.backgroundColor = Colors.veryVeryLightGray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 35.713043 | 94 | 0.694668 |
9cb4e0cbe988339fe4fb56560d4ca53fcbc6bd33 | 2,870 | //
// AppDelegate.swift
// PokedexGo
//
// Created by Yi Gu on 7/10/16.
// Copyright © 2016 yigu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let splitViewController = self.window!.rootViewController as! UISplitViewController
let leftNavController = splitViewController.viewControllers.first as! UINavigationController
let masterViewController = leftNavController.topViewController as! MasterViewController
let rightNavController = splitViewController.viewControllers.last as! UINavigationController
let detailViewController = rightNavController.topViewController as! DetailViewController
let firstPokemon = masterViewController.pokemons.first
detailViewController.pokemon = firstPokemon
masterViewController.delegate = detailViewController
detailViewController.navigationItem.leftItemsSupplementBackButton = true
detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.290323 | 281 | 0.78885 |
2fbc3b16ad1147b1d60ee8613aae208fa024ec51 | 2,617 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Original source:
// "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms"
// Han Xiao and Kashif Rasul and Roland Vollgraf
// https://arxiv.org/abs/1708.07747
import Foundation
import TensorFlow
import Batcher
public struct OldFashionMNIST: ImageClassificationDataset {
public typealias SourceDataSet = [TensorPair<Float, Int32>]
public let training: Batcher<SourceDataSet>
public let test: Batcher<SourceDataSet>
public init(batchSize: Int) {
self.init(batchSize: batchSize, flattening: false, normalizing: false)
}
public init(
batchSize: Int, flattening: Bool = false, normalizing: Bool = false,
localStorageDirectory: URL = DatasetUtilities.defaultDirectory
.appendingPathComponent("FashionMNIST", isDirectory: true)
) {
training = Batcher<SourceDataSet>(
on: oldFetchMNISTDataset(
localStorageDirectory: localStorageDirectory,
remoteBaseDirectory: "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/",
imagesFilename: "train-images-idx3-ubyte",
labelsFilename: "train-labels-idx1-ubyte",
flattening: flattening,
normalizing: normalizing),
batchSize: batchSize,
numWorkers: 1, //No need to use parallelism since everything is loaded in memory
shuffle: true)
test = Batcher<SourceDataSet>(
on: oldFetchMNISTDataset(
localStorageDirectory: localStorageDirectory,
remoteBaseDirectory: "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/",
imagesFilename: "t10k-images-idx3-ubyte",
labelsFilename: "t10k-labels-idx1-ubyte",
flattening: flattening,
normalizing: normalizing),
batchSize: batchSize,
numWorkers: 1) //No need to use parallelism since everything is loaded in memory
}
} | 44.355932 | 99 | 0.679786 |
7253728f632c70a3effc2c06ebf53783730522c2 | 1,805 | //
// RelationshipProtocol.swift
// CoreStore
//
// Copyright © 2017 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - RelationshipProtocol
internal protocol RelationshipProtocol: class {
var keyPath: KeyPathString { get }
var isToMany: Bool { get }
var isOrdered: Bool { get }
var deleteRule: NSDeleteRule { get }
var inverse: (type: CoreStoreObject.Type, keyPath: () -> KeyPathString?) { get }
var affectedByKeyPaths: () -> Set<String> { get }
var parentObject: CoreStoreObject? { get set }
var versionHashModifier: () -> String? { get }
var renamingIdentifier: () -> String? { get }
var minCount: Int { get }
var maxCount: Int { get }
}
| 39.23913 | 84 | 0.71856 |
ff98dc07b6e38b57afdb10f9e976e5908399b078 | 755 | import RediStack
import AsyncKit
import Foundation
// MARK: JSON
extension RedisClient {
/// Gets key as a decodable type.
public func get<D>(_ key: RedisKey, asJSON type: D.Type) -> EventLoopFuture<D?> where D: Decodable {
return get(key, as: Data.self).flatMapThrowing { data in
return try data.flatMap { data in
return try JSONDecoder().decode(D.self, from: data)
}
}
}
/// Sets key to an encodable item.
public func set<E>(_ key: RedisKey, toJSON entity: E) -> EventLoopFuture<Void> where E: Encodable {
do {
return try set(key, to: JSONEncoder().encode(entity))
} catch {
return eventLoop.makeFailedFuture(error)
}
}
}
| 29.038462 | 104 | 0.603974 |
03a4c4b521af0b1c37a9e136914f3c045a5c1f72 | 16,004 | //
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import UIKit
import ArcGIS
class ViewController: UIViewController, AGSMapViewLayerDelegate, AGSRouteTaskDelegate, AGSMapViewTouchDelegate {
@IBOutlet weak var mapView: AGSMapView!
@IBOutlet weak var directionsLabel: UILabel!
@IBOutlet weak var prevBtn: UIBarButtonItem!
@IBOutlet weak var nextBtn: UIBarButtonItem!
@IBOutlet weak var reorderBtn: UIBarButtonItem!
var graphicsLayerStops:AGSGraphicsLayer!
var graphicsLayerRoute:AGSGraphicsLayer!
var routeTask:AGSRouteTask!
var routeTaskParams:AGSRouteTaskParameters!
var currentDirectionGraphic:AGSDirectionGraphic!
var routeResult:AGSRouteResult!
var lastStop:AGSGraphic!
var isExecuting = false
var routeGraphic:AGSGraphic!
var numStops:UInt = 0
var directionIndex:Int = 0
var reorderStops = false
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.showMagnifierOnTapAndHold = true
self.mapView.allowMagnifierToPanMap = false
self.mapView.layerDelegate = self
// Load a tiled map service
self.mapView.addMapLayer(AGSLocalTiledLayer(name: "SanFrancisco.tpk"))
// Setup the route task
var error:NSError? = nil
self.routeTask = AGSRouteTask(databaseName: "RuntimeSanFrancisco", network:"Streets_ND", error:&error)
// assign delegate to this view controller
self.routeTask.delegate = self
// kick off asynchronous method to retrieve default parameters
// for the route task
self.routeTask.retrieveDefaultRouteTaskParameters()
// add graphics layer for displaying the route
var cs = AGSCompositeSymbol()
var sls1 = AGSSimpleLineSymbol()
sls1.color = UIColor.yellowColor()
sls1.style = .Solid
sls1.width = 8
cs.addSymbol(sls1)
var sls2 = AGSSimpleLineSymbol()
sls2.color = UIColor.blueColor()
sls2.style = .Solid
sls2.width = 4
cs.addSymbol(sls2)
self.graphicsLayerRoute = AGSGraphicsLayer()
self.graphicsLayerRoute.renderer = AGSSimpleRenderer(symbol: cs)
self.mapView.addMapLayer(self.graphicsLayerRoute, withName:"Route")
// add graphics layer for displaying the stops
self.graphicsLayerStops = AGSGraphicsLayer()
self.mapView.addMapLayer(self.graphicsLayerStops, withName:"Stops")
// initialize stop counter
self.numStops = 0
// update our banner
self.updateDirectionsLabel("Tap & hold on the map to add stops")
self.directionsLabel.hidden = false
self.mapView.touchDelegate = self
self.isExecuting = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - AGSMapViewTouchDelegate
func mapView(mapView: AGSMapView!, didTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
self.lastStop = self.addStop(mappoint)
if self.graphicsLayerStops.graphics.count > 1 {
self.isExecuting = true
self.solveRoute()
}
}
func mapView(mapView: AGSMapView!, didMoveTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
if self.isExecuting {
return
}
self.lastStop.geometry = mappoint
if self.graphicsLayerStops.graphics.count < 2 {
return
}
self.isExecuting = true
self.solveRoute()
}
func mapView(mapView: AGSMapView!, didEndTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
if self.graphicsLayerStops.graphics.count < 2 {
self.reorderBtn.enabled = false
}
else {
self.reorderBtn.enabled = true
}
}
//MARK: - AGSMapViewLayerDelegate
func mapViewDidLoad(mapView: AGSMapView!) {
var museumOfMA = AGSPoint(fromDecimalDegreesString: "37.785 , -122.400", withSpatialReference:AGSSpatialReference.wgs84SpatialReference())
self.addStop((AGSGeometryEngine.defaultGeometryEngine().projectGeometry(museumOfMA, toSpatialReference: self.mapView.spatialReference)) as AGSPoint)
if self.routeTaskParams != nil {
self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
}
mapView.zoomIn(false);
}
//MARK: - AGSRouteTaskDelegate
//
// we got the default parameters from the service
//
func routeTask(routeTask: AGSRouteTask!, operation op: NSOperation!, didRetrieveDefaultRouteTaskParameters routeParams: AGSRouteTaskParameters!) {
self.routeTaskParams = routeParams
self.routeTaskParams.returnRouteGraphics = true
// this returns turn-by-turn directions
self.routeTaskParams.returnDirections = true
self.routeTaskParams.findBestSequence = false
self.routeTaskParams.impedanceAttributeName = "Minutes"
self.routeTaskParams.accumulateAttributeNames = ["Meters", "Minutes"]
// since we used "findBestSequence" we need to
// get the newly reordered stops
self.routeTaskParams.returnStopGraphics = false
// ensure the graphics are returned in our map's spatial reference
self.routeTaskParams.outSpatialReference = self.mapView.spatialReference
// let's ignore invalid locations
self.routeTaskParams.ignoreInvalidLocations = true
}
//
// an error was encountered while getting defaults
//
func routeTask(routeTask: AGSRouteTask!, operation op: NSOperation!, didFailToRetrieveDefaultRouteTaskParametersWithError error: NSError!) {
// Create an alert to let the user know the retrieval failed
dispatch_async(dispatch_get_main_queue(), { () -> Void in
UIAlertView(title: "Error", message: "Failed to retrieve default route parameters", delegate: nil, cancelButtonTitle: "OK").show()
println("Failed to retrieve default route parameters: \(error)")
})
}
//
// route was solved
//
func routeTask(routeTask: AGSRouteTask!, operation op: NSOperation!, didSolveWithResult routeTaskResult: AGSRouteTaskResult!) {
// update our banner with status
self.updateDirectionsLabel("Routing completed")
// we know that we are only dealing with 1 route...
self.routeResult = routeTaskResult.routeResults.last as AGSRouteResult
var resultSummary = "\(self.routeResult.totalMinutes) mins, \(self.routeResult.totalMiles) miles"
self.updateDirectionsLabel(resultSummary)
// add the route graphic to the graphic's layer
self.graphicsLayerRoute.removeAllGraphics()
self.graphicsLayerRoute.addGraphic(self.routeResult.routeGraphic)
// enable the next button so the user can traverse directions
self.nextBtn.enabled = true
if self.routeResult.stopGraphics != nil {
self.graphicsLayerStops.removeAllGraphics()
for reorderedStop in self.routeResult.stopGraphics as [AGSStopGraphic] {
var exists:ObjCBool = false
var sequence = UInt(reorderedStop.attributeAsIntegerForKey("Sequence", exists: &exists))
// create a composite symbol using the sequence number
reorderedStop.symbol = self.stopSymbolWithNumber(sequence)
// add the graphic
self.graphicsLayerStops.addGraphic(reorderedStop)
}
self.routeTaskParams.findBestSequence = false
self.routeTaskParams.returnStopGraphics = false
}
self.isExecuting = false
}
//
// solve failed
//
func routeTask(routeTask: AGSRouteTask!, operation op: NSOperation!, didFailSolveWithError error: NSError!) {
self.updateDirectionsLabel("Routing failed")
// the solve route failed...
// let the user know
UIAlertView(title: "Solve Route Failed", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show()
}
//MARK: - Misc
//
// create a composite symbol with a number
//
func stopSymbolWithNumber(stopNumber:UInt) -> AGSCompositeSymbol {
var cs = AGSCompositeSymbol()
// create outline
var sls = AGSSimpleLineSymbol()
sls.color = UIColor.blackColor()
sls.width = 2
sls.style = .Solid
// create main circle
var sms = AGSSimpleMarkerSymbol()
sms.color = UIColor.greenColor()
sms.outline = sls
sms.size = CGSizeMake(20, 20)
sms.style = .Circle
cs.addSymbol(sms)
// // add number as a text symbol
var ts = AGSTextSymbol(text: "\(stopNumber)", color: UIColor.blackColor())
ts.vAlignment = .Middle
ts.hAlignment = .Center
ts.fontSize = 16
cs.addSymbol(ts)
return cs
}
//
// represents the current direction
//
func currentDirectionSymbol() -> AGSCompositeSymbol {
var cs = AGSCompositeSymbol()
var sls1 = AGSSimpleLineSymbol()
sls1.color = UIColor.whiteColor()
sls1.style = .Solid
sls1.width = 8
cs.addSymbol(sls1)
var sls2 = AGSSimpleLineSymbol()
sls2.color = UIColor.redColor()
sls2.style = .Dash
sls2.width = 4
cs.addSymbol(sls2)
return cs
}
//
// update our banner's text
//
func updateDirectionsLabel(newLabel:String) {
self.directionsLabel.text = newLabel
}
func addStop(geometry:AGSPoint) -> AGSGraphic {
//grab the geometry, then clear the sketch
//Prepare symbol and attributes for the Stop/Barrier
self.numStops++
var symbol = self.stopSymbolWithNumber(self.numStops)
var stopGraphic = AGSStopGraphic(geometry: geometry, symbol:symbol, attributes:nil)
stopGraphic.sequence = self.numStops
//You can set additional properties on the stop here
//refer to the conceptual helf for Routing task
self.graphicsLayerStops.addGraphic(stopGraphic)
return stopGraphic
}
//
// perform the route task's solve operation
//
func solveRoute() {
self.resetDirections()
var stops = [AGSStopGraphic]()
// get the stop, barriers for the route task
for graphic in self.graphicsLayerStops.graphics as [AGSGraphic] {
// if it's a stop graphic, add the object to stops
if graphic is AGSStopGraphic {
stops.append(graphic as AGSStopGraphic)
}
}
// set the stop and polygon barriers on the parameters object
if stops.count > 0 {
// update our banner
self.updateDirectionsLabel("Routing...")
self.routeTaskParams.setStopsWithFeatures(stops)
// execute the route task
self.routeTask.solveWithParameters(self.routeTaskParams)
}
}
//
// reset the sample so we can perform another route
//
func reset() {
// set stop counter back to 0
self.numStops = 0
// remove all graphics
self.graphicsLayerStops.removeAllGraphics()
self.graphicsLayerRoute.removeAllGraphics()
self.resetDirections()
self.updateDirectionsLabel("Tap & hold on the map to add stops")
self.reorderBtn.enabled = false
}
func resetDirections() {
// disable the next/prev direction buttons
// reset direction index
self.directionIndex = 0
self.nextBtn.enabled = false
self.prevBtn.enabled = false
self.graphicsLayerRoute.removeGraphic(self.currentDirectionGraphic)
}
//MARK: Actions
@IBAction func resetBtnClicked(sender: AnyObject) {
self.reset()
}
@IBAction func nextBtnClicked(sender: AnyObject) {
self.directionIndex++
// remove current direction graphic, so we can display next one
self.graphicsLayerRoute.removeGraphic(self.currentDirectionGraphic)
// get current direction and add it to the graphics layer
var directions = self.routeResult.directions
self.currentDirectionGraphic = directions.graphics[self.directionIndex] as AGSDirectionGraphic
self.currentDirectionGraphic.symbol = self.currentDirectionSymbol()
self.graphicsLayerRoute.addGraphic(self.currentDirectionGraphic)
// update banner
self.updateDirectionsLabel(self.currentDirectionGraphic.text)
self.mapView.zoomToGeometry(self.currentDirectionGraphic.geometry, withPadding:20, animated:true)
// determine if we need to disable a next/prev button
var count = self.routeResult.directions.graphics.count
if self.directionIndex >= (count - 1) {
self.nextBtn.enabled = false
}
if self.directionIndex > 0 {
self.prevBtn.enabled = true
}
}
@IBAction func prevBtnClicked(sender: AnyObject) {
self.directionIndex--
// remove current direction graphic, so we can display next one
self.graphicsLayerRoute.removeGraphic(self.currentDirectionGraphic)
// get next direction
var directions = self.routeResult.directions
self.currentDirectionGraphic = directions.graphics[self.directionIndex] as AGSDirectionGraphic
self.currentDirectionGraphic.symbol = self.currentDirectionSymbol()
self.graphicsLayerRoute.addGraphic(self.currentDirectionGraphic)
// update banner text
self.updateDirectionsLabel(self.currentDirectionGraphic.text)
self.mapView.zoomToGeometry(self.currentDirectionGraphic.geometry, withPadding:20, animated:true)
// determine if we need to disable next/prev button
if self.directionIndex <= 0 {
self.prevBtn.enabled = false
}
if self.directionIndex < self.routeResult.directions.graphics.count - 1 {
self.nextBtn.enabled = true
}
}
@IBAction func routePreferenceChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
self.routeTaskParams.impedanceAttributeName = "Minutes"
break;
case 1:
self.routeTaskParams.impedanceAttributeName = "Meters"
default:
break;
}
self.solveRoute()
}
@IBAction func reorderStops(sender: AnyObject) {
self.routeTaskParams.findBestSequence = true
self.routeTaskParams.preserveFirstStop = false
self.routeTaskParams.preserveLastStop = false
self.routeTaskParams.returnStopGraphics = true
self.solveRoute()
}
}
| 35.564444 | 156 | 0.63859 |
fcce8fd44495f007ecc6813f8207f1f0c6622fd6 | 538 | import UIKit
extension UIView.AnimationCurve {
var animationOptions: UIView.AnimationOptions {
switch self {
case .easeInOut:
return UIView.AnimationOptions.curveEaseInOut
case .easeIn: return
UIView.AnimationOptions.curveEaseIn
case .easeOut: return
UIView.AnimationOptions.curveEaseOut
case .linear:
return UIView.AnimationOptions.curveLinear
@unknown default:
return UIView.AnimationOptions.curveLinear
}
}
}
| 26.9 | 57 | 0.64684 |
715d21065749680f3628eaddf8798b40885f9e5a | 3,912 | //
// SignupViewController.swift
// Hana
//
// Created by ccsuser02 on 2018/07/27.
//
import UIKit
class SignupViewController: UIViewController {
private let usecase = LoginUseCase()
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var usernameExistenceImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
scrollView.backgroundColor = HanaBackgroundColor
signupButton.setTitleColor(HanaWhiteTextColor, for: .normal)
signupButton.setBackgroundImage(UIImage.colorImage(color: HanaDisabelColor, size: CGSize(width: 100, height: 100)), for: .disabled)
signupButton.setBackgroundImage(UIImage.colorImage(color: HanaMainRedColor, size: CGSize(width: 100, height: 100)), for: .normal)
usernameTextField.rx.controlEvent(UIControlEvents.editingDidEnd).asDriver().drive(onNext: { (event) in
self.usecase.existenceUsername(closure: { (isSuccess) in
self.usernameExistenceImageView.image = isSuccess ? #imageLiteral(resourceName: "icon_signup_check_mark"):#imageLiteral(resourceName: "icon_signup_x_mark")
self.usernameExistenceImageView.isHidden = false
})
}).disposed(by: usecase.disposeBag)
_ = usernameTextField.rx.text.map { $0 ?? "" }.bind(to: usecase.model.username)
_ = passwordTextField.rx.text.map { $0 ?? "" }.bind(to: usecase.model.password)
_ = confirmPasswordTextField.rx.text.map { $0 ?? "" }.bind(to: usecase.model.confirmPassword)
usecase.signupValueChanged { (isEmpty) in
self.signupButton.isEnabled = !isEmpty
}
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillShow).asObservable().subscribe { (notification) in
let info = notification.element!.userInfo!
let value = info[UIKeyboardFrameEndUserInfoKey]! as! CGRect
self.didChangeScrollView(height: value.size.height)
}.disposed(by: usecase.disposeBag)
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillHide).asObservable().subscribe { (notification) in
self.returnScrollView()
}.disposed(by: usecase.disposeBag)
}
private func didChangeScrollView(height: CGFloat) {
scrollView.contentOffset = CGPoint(x: 0, y: height)
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
}
private func returnScrollView() {
scrollView.contentInset = UIEdgeInsets.zero
}
@IBAction func signupTapped(_ sender: UIButton) {
usecase.signup { (isSuccess) in
self.moveToEditUserInfo()
}
}
@IBAction func backTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func moveToEditUserInfo() {
if let viewController = R.storyboard.editUserInfo.instantiateInitialViewController() {
present(viewController, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 36.90566 | 171 | 0.667178 |
fcfc1b2e5f8c03418f8d487bbf3bcde2a1159132 | 280 | //
// PresentiRPCDelegate.swift
// Discord-Apple Music Rich Presence
//
// Created by Eric Rabil on 5/17/20.
// Copyright © 2020 Ayden Panhuyzen. All rights reserved.
//
import Foundation
protocol PresentiRPCDelegate {
func rpcDidConnect()
func rpcDidDisconnect()
}
| 18.666667 | 58 | 0.721429 |
610ba30e07ec2975016c7a41b0a10b087625fe2d | 1,653 | //
// BaseService.swift
// RemoteCore_Example
//
// Created by GBS Technology on 6/1/22.
// Copyright © 2022 CocoaPods. All rights reserved.
//
import Foundation
import RemoteCore
import Alamofire
class BaseService : RCDefaultService {
override var headers: HTTPHeaders {
.init()
}
}
class DemoClass{
private let baseService = BaseService()
func test() {
fetchPost()
}
private func fetchPost() {
let paramConfig : RCParameterConfigure<PostResponse<Post>> =
.init(url: "https://gorest.co.in/public/v1/posts",
page: 1,
limit: 20,
debug: false) { result in
switch result {
case .success(let data):
print(#function,data?.data.count ?? 0)
break
case .failure(let err):
print(#function,err.message)
break
}
}
baseService.fetchItems(with: paramConfig)
}
}
class RemoteClassDemo {
private let rcRemote = RCRemote()
func fetchItem() {
let config = RCConfigure<PostResponse<Post>>.init(url: "https://gorest.co.in/public/v1/posts",headers: .default,debug: true) { result in
switch result {
case .success(let data):
print(data?.data ?? [])
break
case .failure(let err):
print(err.message)
break
}
}
rcRemote.request(configuration: config)
}
}
class Test
{
}
| 19.915663 | 144 | 0.509982 |
162b3ee28e57494eecad1ebae9d5206f2721a5a0 | 2,197 | //
// Copyright (c) 2018 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//-------------------------------------------------------------------------------------------------------------------------------------------------
class DBCall: RLMObject {
@objc dynamic var objectId = ""
@objc dynamic var initiatorId = ""
@objc dynamic var recipientId = ""
@objc dynamic var phoneNumber = ""
@objc dynamic var type = ""
@objc dynamic var text = ""
@objc dynamic var status = ""
@objc dynamic var duration: Int = 0
@objc dynamic var startedAt: Int64 = 0
@objc dynamic var establishedAt: Int64 = 0
@objc dynamic var endedAt: Int64 = 0
@objc dynamic var isDeleted = false
@objc dynamic var createdAt: Int64 = 0
@objc dynamic var updatedAt: Int64 = 0
//---------------------------------------------------------------------------------------------------------------------------------------------
class func lastUpdatedAt() -> Int64 {
let dbcall = DBCall.allObjects().sortedResults(usingKeyPath: "updatedAt", ascending: true).lastObject() as? DBCall
return dbcall?.updatedAt ?? 0
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override static func primaryKey() -> String? {
return FCALL_OBJECTID
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func updateItem(isDeleted isDeleted_: Bool) {
do {
let realm = RLMRealm.default()
realm.beginWriteTransaction()
isDeleted = isDeleted_
try realm.commitWriteTransaction()
} catch {
ProgressHUD.showError("Realm commit error.")
}
}
}
| 35.435484 | 147 | 0.527993 |
39cf81215318514dc90dbd348d2b02ec21ba046e | 4,706 | //******************************************************************************
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// inspired by the C implementation of Paulius Micikevicius [email protected]
//
// *** TODO *** we need to decide how numerically correct we want to
// emulate Float16 and BFloat16
public struct BFloat16:
Equatable,
Comparable,
AdditiveArithmetic,
ExpressibleByFloatLiteral,
ExpressibleByIntegerLiteral
{
// properties
public let x: UInt16
//--------------------------------------------------------------------------
// initializers
@inlinable public init(_ v: Float) {
self = Self.float2bfloat16_rn(v)
}
@inlinable public init(bitPattern: UInt16) { x = bitPattern }
@inlinable public init?(_ string: String) {
guard let v = Float(string) else { return nil }
self.init(v)
}
@inlinable public init(floatLiteral value: Double) {
self.init(Float(value))
}
@inlinable public init(integerLiteral value: Int) {
self.init(Float(value))
}
//--------------------------------------------------------------------------
@inlinable public static func float2bfloat16_rn(_ v: Float) -> BFloat16 {
var raw: UInt16 = 0
var remainder: UInt32 = 0
raw = Self.float2bfloat16(v, &remainder)
if (remainder > UInt32(0x8000_0000))
|| ((remainder == UInt32(0x8000_0000)) && ((raw & UInt16(1)) != UInt32(0)))
{
raw += 1
}
return BFloat16(bitPattern: raw)
}
//--------------------------------------------------------------------------
@usableFromInline static func float2bfloat16(
_ f: Float,
_ rem: inout UInt32
) -> UInt16 {
let x = UInt32(f.bitPattern)
if (x & UInt32(0x7fff_ffff)) > UInt32(0x7f80_0000) {
rem = 0
return UInt16(0x7fff)
} else {
rem = x << 16
return UInt16(x >> 16)
}
}
//--------------------------------------------------------------------------
@inlinable public static func bfloat162float(_ v: BFloat16) -> Float {
Float(bitPattern: UInt32(v.x) << 16)
}
//--------------------------------------------------------------------------
// functions
@inlinable public static func < (lhs: BFloat16, rhs: BFloat16) -> Bool {
Float(lhs) < Float(rhs)
}
@inlinable public static func == (lhs: BFloat16, rhs: BFloat16) -> Bool {
lhs.x == rhs.x
}
// operators
@inlinable public static func + (lhs: BFloat16, rhs: BFloat16) -> BFloat16 {
BFloat16(Float(lhs) + Float(rhs))
}
@inlinable public static func - (lhs: BFloat16, rhs: BFloat16) -> BFloat16 {
BFloat16(Float(lhs) - Float(rhs))
}
@inlinable public static func * (lhs: BFloat16, rhs: BFloat16) -> BFloat16 {
BFloat16(Float(lhs) * Float(rhs))
}
@inlinable public static func / (lhs: BFloat16, rhs: BFloat16) -> BFloat16 {
BFloat16(Float(lhs) / Float(rhs))
}
}
extension Float {
@inlinable public init(_ value: BFloat16) {
self.init(BFloat16.bfloat162float(value))
}
}
//==============================================================================
// BFloat16
extension BFloat16: StorageElement {
@inlinable public static func storedIndex(_ index: Int) -> Int { index }
@inlinable public static func storedCount(_ count: Int) -> Int { count }
@inlinable public static func alignment(_ index: Int) -> Int { 0 }
//-------------------------------------
// accessors
@inlinable public static func value(
at index: Int, from stored: Self
) -> Float { Float(stored) }
@inlinable public static func store(
value: Float, at index: Int, to stored: inout Self
) { stored = Self(value) }
@inlinable public static func stored(value: Float) -> Self { Self(value) }
@inlinable public static func storedRange(start: Int, count: Int)
-> (storedStart: Int, storedCount: Int)
{ (start, count) }
@inlinable public static func getValue(
from buffer: UnsafeBufferPointer<BFloat16>,
at index: Int
) -> Float {
Float(buffer[index])
}
@inlinable public static func set(
value: Float,
in buffer: UnsafeMutableBufferPointer<BFloat16>,
at index: Int
) {
buffer[index] = BFloat16(value)
}
}
| 29.229814 | 81 | 0.582873 |
11adb5306164894f2d62f42f1ad4b5307113fe3e | 9,599 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import Beagle
import BeagleSchema
final class RepositoryTests: XCTestCase {
private var dependencies = BeagleDependencies()
private lazy var sut = RepositoryDefault(dependencies: dependencies)
private let url = "www.something.com"
// swiftlint:disable force_unwrapping
func test_requestWithInvalidURL_itShouldFail() {
// Given
let invalidURL = "🥶"
let beagleDependencies = BeagleDependencies()
beagleDependencies.urlBuilder = UrlBuilderStub(baseUrl: nil, resultURL: nil)
let repository = RepositoryDefault(dependencies: beagleDependencies)
let fetchComponentExpectation = expectation(description: "fetchComponent")
var fetchError: Request.Error?
let expectedError = Request.Error.urlBuilderError
// When
repository.fetchComponent(url: invalidURL, additionalData: nil) {
if case let .failure(error) = $0 {
fetchError = error
}
fetchComponentExpectation.fulfill()
}
let submitFormExpectation = expectation(description: "submitForm")
var formError: Request.Error?
let formData = Request.FormData(
method: .post, values: [:]
)
repository.submitForm(url: invalidURL, additionalData: nil, data: formData) {
if case let .failure(error) = $0 {
formError = error
}
submitFormExpectation.fulfill()
}
wait(for: [fetchComponentExpectation, submitFormExpectation], timeout: 1.0)
// Then
XCTAssertEqual(expectedError.localizedDescription, fetchError?.localizedDescription)
XCTAssertEqual(expectedError.localizedDescription, formError?.localizedDescription)
}
func test_whenRequestSucceeds_withValidData_itShouldReturnSomeComponent() {
// Given
let jsonData = """
{
"_beagleComponent_": "beagle:text",
"text": "some text"
}
""".data(using: .utf8)!
dependencies.networkClient = NetworkClientStub(result:
.success(.init(data: jsonData, response: URLResponse()))
)
let expec = expectation(description: "fetchComponentExpectation")
// When
var componentReturned: ServerDrivenComponent?
sut.fetchComponent(url: url, additionalData: nil) { result in
if case .success(let component) = result {
componentReturned = component
}
expec.fulfill()
}
wait(for: [expec], timeout: 1.0)
// Then
XCTAssertNotNil(componentReturned)
XCTAssert(componentReturned is Text)
}
func test_whenRequestSucceeds_butTheDecodingFailsWithAnError_itShouldThrowDecodingError() {
// Given
dependencies.networkClient = NetworkClientStub(result:
.success(.init(data: Data(), response: URLResponse()))
)
let decoderStub = ComponentDecodingStub()
decoderStub.errorToThrowOnDecode = NSError(domain: "Mock", code: 1, description: "Mock")
dependencies.decoder = decoderStub
let expec = expectation(description: "fetch")
// When
var errorThrown: Request.Error?
sut.fetchComponent(url: url, additionalData: nil) { result in
if case let .failure(error) = result {
errorThrown = error
}
expec.fulfill()
}
wait(for: [expec], timeout: 1.0)
// Then
XCTAssertNotNil(errorThrown)
guard case .decoding? = errorThrown else {
XCTFail("Expected a `.decoding` error, but got \(String(describing: errorThrown)).")
return
}
}
func test_shouldAddAdditionalDataToRequest() {
// Given
let body = "{}".data(using: .utf8)!
let clientStub = NetworkClientStub(result: .success(.init(data: body, response: URLResponse())))
dependencies.networkClient = clientStub
let additionalData = HttpAdditionalData(
httpData: .init(method: .POST, body: body),
headers: ["headerKey": "headerValue"]
)
let expec = expectation(description: "fetch")
// When
sut.fetchComponent(url: url, additionalData: additionalData) { _ in
expec.fulfill()
}
wait(for: [expec], timeout: 1.0)
// Then
let expectedData = clientStub.executedRequest?.additionalData as? HttpAdditionalData
XCTAssertEqual(expectedData, additionalData)
XCTAssertEqual(clientStub.executedRequest?.url.absoluteString, url)
}
}
// MARK: - Testing Helpers
final class ComponentDecodingStub: ComponentDecoding {
func register<T>(component type: T.Type) where T: RawComponent {}
func register<A>(action type: A.Type) where A: RawAction {}
func register<T>(component type: T.Type, named typeName: String) where T: BeagleSchema.RawComponent {}
func register<A>(action type: A.Type, named typeName: String) where A: BeagleSchema.RawAction {}
func componentType(forType type: String) -> Decodable.Type? { return nil }
func actionType(forType type: String) -> Decodable.Type? { return nil }
var componentToReturnOnDecode: BeagleSchema.RawComponent?
var errorToThrowOnDecode: Error?
func decodeComponent(from data: Data) throws -> BeagleSchema.RawComponent {
if let error = errorToThrowOnDecode {
throw error
}
return ComponentDummy()
}
func decodeAction(from data: Data) throws -> RawAction {
if let error = errorToThrowOnDecode {
throw error
}
return ActionDummy()
}
}
final class RepositoryStub: Repository {
var componentResult: Result<ServerDrivenComponent, Request.Error>?
var formResult: Result<RawAction, Request.Error>?
private(set) var didCallDispatch = false
private(set) var token = Token()
private(set) var formData = Request.FormData(method: .post, values: [:])
class Token: RequestToken {
var didCallCancel = false
func cancel() {
didCallCancel = true
}
}
init(
componentResult: Result<ServerDrivenComponent, Request.Error>? = nil,
formResult: Result<RawAction, Request.Error>? = nil
) {
self.componentResult = componentResult
self.formResult = formResult
}
func fetchComponent(
url: String,
additionalData: RemoteScreenAdditionalData?,
useCache: Bool,
completion: @escaping (Result<ServerDrivenComponent, Request.Error>) -> Void
) -> RequestToken? {
didCallDispatch = true
if let result = componentResult {
completion(result)
}
return token
}
func submitForm(
url: String,
additionalData: RemoteScreenAdditionalData?,
data: Request.FormData,
completion: @escaping (Result<RawAction, Request.Error>) -> Void
) -> RequestToken? {
didCallDispatch = true
formData = data
if let result = formResult {
completion(result)
}
return token
}
func fetchImage(
url: String,
additionalData: RemoteScreenAdditionalData?,
completion: @escaping (Result<Data, Request.Error>) -> Void
) -> RequestToken? {
return nil
}
}
class NetworkClientStub: NetworkClient {
let result: NetworkClient.NetworkResult
private(set) var executedRequest: Request?
init(result: NetworkClient.NetworkResult) {
self.result = result
}
func executeRequest(_ request: Request, completion: @escaping RequestCompletion) -> RequestToken? {
executedRequest = request
completion(result)
return nil
}
}
enum TestErrors: Swift.Error {
case generic
}
class CacheManagerSpy: CacheManagerProtocol {
var references = [Reference]()
class Reference {
let cache: CacheReference
var isValid: Bool
init(cache: CacheReference, isValid: Bool) {
self.cache = cache
self.isValid = isValid
}
}
func addToCache(_ reference: CacheReference) {
guard first(reference.identifier) == nil else { return }
references.append(.init(cache: reference, isValid: false))
}
func getReference(identifiedBy id: String) -> CacheReference? {
return first(id)?.cache
}
func isValid(reference: CacheReference) -> Bool {
return first(reference.identifier)?.isValid ?? false
}
private func first(_ id: String) -> Reference? {
return references.first { $0.cache.identifier == id }
}
}
private struct UrlBuilderStub: UrlBuilderProtocol {
var baseUrl: URL?
var resultURL: URL?
func build(path: String) -> URL? {
return resultURL
}
}
| 31.369281 | 106 | 0.63642 |
2098c5fd9ebd1ff874edd3cb9786e9b6dfb7b20f | 459 | //
// AnyObject30WireFrame.swift
// AnyObject
//
// Created by 19205313 on 25.05.2021.
//
import UIKit
final class AnyObject30WireFrame {
}
// MARK: - AnyObject30WireFrameProtocol
extension AnyObject30WireFrame: AnyObject30WireFrameProtocol {
// func present_XXX(from view: AnyObject30ViewProtocol?) {
// guard let controller = view as? UIViewController else {
// return
// }
//
// }
}
| 19.125 | 69 | 0.625272 |
fc61df7a96793368d2d1a081fe9cb1c85567c24b | 3,594 | import AuthenticationClient
import Combine
import ComposableArchitecture
import LoginCore
import TicTacToeCommon
import XCTest
@testable import LoginSwiftUI
class LoginSwiftUITests: XCTestCase {
let scheduler = DispatchQueue.testScheduler
func testFlow_Success() {
let store = TestStore(
initialState: LoginState(),
reducer: loginReducer,
environment: LoginEnvironment(
authenticationClient: .mock(
login: { _ in
Effect(value: .init(token: "deadbeefdeadbeef", twoFactorRequired: false))
}
),
mainQueue: .init(self.scheduler)
)
)
.scope(state: { $0.view }, action: LoginAction.view)
store.assert(
.send(.emailChanged("[email protected]")) {
$0.email = "[email protected]"
},
.send(.passwordChanged("password")) {
$0.password = "password"
$0.isLoginButtonDisabled = false
},
.send(.loginButtonTapped) {
$0.isActivityIndicatorVisible = true
$0.isFormDisabled = true
},
.do {
self.scheduler.advance()
},
.receive(.loginResponse(.success(.init(token: "deadbeefdeadbeef", twoFactorRequired: false))))
{
$0.isActivityIndicatorVisible = false
$0.isFormDisabled = false
}
)
}
func testFlow_Success_TwoFactor() {
let store = TestStore(
initialState: LoginState(),
reducer: loginReducer,
environment: LoginEnvironment(
authenticationClient: .mock(
login: { _ in
Effect(value: .init(token: "deadbeefdeadbeef", twoFactorRequired: true))
}
),
mainQueue: .init(self.scheduler)
)
)
.scope(state: { $0.view }, action: LoginAction.view)
store.assert(
.send(.emailChanged("[email protected]")) {
$0.email = "[email protected]"
},
.send(.passwordChanged("password")) {
$0.password = "password"
$0.isLoginButtonDisabled = false
},
.send(.loginButtonTapped) {
$0.isActivityIndicatorVisible = true
$0.isFormDisabled = true
},
.do {
self.scheduler.advance()
},
.receive(.loginResponse(.success(.init(token: "deadbeefdeadbeef", twoFactorRequired: true))))
{
$0.isActivityIndicatorVisible = false
$0.isFormDisabled = false
$0.isTwoFactorActive = true
},
.send(.twoFactorDismissed) {
$0.isTwoFactorActive = false
}
)
}
func testFlow_Failure() {
let store = TestStore(
initialState: LoginState(),
reducer: loginReducer,
environment: LoginEnvironment(
authenticationClient: .mock(
login: { _ in Effect(error: .invalidUserPassword) }
),
mainQueue: .init(self.scheduler)
)
)
.scope(state: { $0.view }, action: LoginAction.view)
store.assert(
.send(.emailChanged("blob")) {
$0.email = "blob"
},
.send(.passwordChanged("password")) {
$0.password = "password"
$0.isLoginButtonDisabled = false
},
.send(.loginButtonTapped) {
$0.isActivityIndicatorVisible = true
$0.isFormDisabled = true
},
.do {
self.scheduler.advance()
},
.receive(.loginResponse(.failure(.invalidUserPassword))) {
$0.alert = .init(title: .init(AuthenticationError.invalidUserPassword.localizedDescription))
$0.isActivityIndicatorVisible = false
$0.isFormDisabled = false
},
.send(.alertDismissed) {
$0.alert = nil
}
)
}
}
| 27.227273 | 100 | 0.595437 |
290471e298a6c639d451eebce413fe7f3bcab960 | 92,864 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal let kCFURLPOSIXPathStyle = CFURLPathStyle.cfurlposixPathStyle
internal let kCFURLWindowsPathStyle = CFURLPathStyle.cfurlWindowsPathStyle
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#endif
// NOTE: this represents PLATFORM_PATH_STYLE
#if os(Windows)
internal let kCFURLPlatformPathStyle = kCFURLWindowsPathStyle
#else
internal let kCFURLPlatformPathStyle = kCFURLPOSIXPathStyle
#endif
private func _standardizedPath(_ path: String) -> String {
if !path.isAbsolutePath {
return path._nsObject.standardizingPath
}
#if os(Windows)
return path.unixPath
#else
return path
#endif
}
internal func _pathComponents(_ path: String?) -> [String]? {
guard let p = path else {
return nil
}
var result = [String]()
if p.length == 0 {
return result
} else {
let characterView = p
var curPos = characterView.startIndex
let endPos = characterView.endIndex
if characterView[curPos] == "/" {
result.append("/")
}
while curPos < endPos {
while curPos < endPos && characterView[curPos] == "/" {
curPos = characterView.index(after: curPos)
}
if curPos == endPos {
break
}
var curEnd = curPos
while curEnd < endPos && characterView[curEnd] != "/" {
curEnd = characterView.index(after: curEnd)
}
result.append(String(characterView[curPos ..< curEnd]))
curPos = curEnd
}
}
if p.length > 1 && p.hasSuffix("/") {
result.append("/")
}
return result
}
public struct URLResourceKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
}
extension URLResourceKey {
public static let keysOfUnsetValuesKey = URLResourceKey(rawValue: "NSURLKeysOfUnsetValuesKey")
public static let nameKey = URLResourceKey(rawValue: "NSURLNameKey")
public static let localizedNameKey = URLResourceKey(rawValue: "NSURLLocalizedNameKey")
public static let isRegularFileKey = URLResourceKey(rawValue: "NSURLIsRegularFileKey")
public static let isDirectoryKey = URLResourceKey(rawValue: "NSURLIsDirectoryKey")
public static let isSymbolicLinkKey = URLResourceKey(rawValue: "NSURLIsSymbolicLinkKey")
public static let isVolumeKey = URLResourceKey(rawValue: "NSURLIsVolumeKey")
public static let isPackageKey = URLResourceKey(rawValue: "NSURLIsPackageKey")
public static let isApplicationKey = URLResourceKey(rawValue: "NSURLIsApplicationKey")
public static let applicationIsScriptableKey = URLResourceKey(rawValue: "NSURLApplicationIsScriptableKey")
public static let isSystemImmutableKey = URLResourceKey(rawValue: "NSURLIsSystemImmutableKey")
public static let isUserImmutableKey = URLResourceKey(rawValue: "NSURLIsUserImmutableKey")
public static let isHiddenKey = URLResourceKey(rawValue: "NSURLIsHiddenKey")
public static let hasHiddenExtensionKey = URLResourceKey(rawValue: "NSURLHasHiddenExtensionKey")
public static let creationDateKey = URLResourceKey(rawValue: "NSURLCreationDateKey")
public static let contentAccessDateKey = URLResourceKey(rawValue: "NSURLContentAccessDateKey")
public static let contentModificationDateKey = URLResourceKey(rawValue: "NSURLContentModificationDateKey")
public static let attributeModificationDateKey = URLResourceKey(rawValue: "NSURLAttributeModificationDateKey")
public static let linkCountKey = URLResourceKey(rawValue: "NSURLLinkCountKey")
public static let parentDirectoryURLKey = URLResourceKey(rawValue: "NSURLParentDirectoryURLKey")
public static let volumeURLKey = URLResourceKey(rawValue: "NSURLVolumeURLKey")
public static let typeIdentifierKey = URLResourceKey(rawValue: "NSURLTypeIdentifierKey")
public static let localizedTypeDescriptionKey = URLResourceKey(rawValue: "NSURLLocalizedTypeDescriptionKey")
public static let labelNumberKey = URLResourceKey(rawValue: "NSURLLabelNumberKey")
public static let labelColorKey = URLResourceKey(rawValue: "NSURLLabelColorKey")
public static let localizedLabelKey = URLResourceKey(rawValue: "NSURLLocalizedLabelKey")
public static let effectiveIconKey = URLResourceKey(rawValue: "NSURLEffectiveIconKey")
public static let customIconKey = URLResourceKey(rawValue: "NSURLCustomIconKey")
public static let fileResourceIdentifierKey = URLResourceKey(rawValue: "NSURLFileResourceIdentifierKey")
public static let volumeIdentifierKey = URLResourceKey(rawValue: "NSURLVolumeIdentifierKey")
public static let preferredIOBlockSizeKey = URLResourceKey(rawValue: "NSURLPreferredIOBlockSizeKey")
public static let isReadableKey = URLResourceKey(rawValue: "NSURLIsReadableKey")
public static let isWritableKey = URLResourceKey(rawValue: "NSURLIsWritableKey")
public static let isExecutableKey = URLResourceKey(rawValue: "NSURLIsExecutableKey")
public static let fileSecurityKey = URLResourceKey(rawValue: "NSURLFileSecurityKey")
public static let isExcludedFromBackupKey = URLResourceKey(rawValue: "NSURLIsExcludedFromBackupKey")
public static let tagNamesKey = URLResourceKey(rawValue: "NSURLTagNamesKey")
public static let pathKey = URLResourceKey(rawValue: "NSURLPathKey")
public static let canonicalPathKey = URLResourceKey(rawValue: "NSURLCanonicalPathKey")
public static let isMountTriggerKey = URLResourceKey(rawValue: "NSURLIsMountTriggerKey")
public static let generationIdentifierKey = URLResourceKey(rawValue: "NSURLGenerationIdentifierKey")
public static let documentIdentifierKey = URLResourceKey(rawValue: "NSURLDocumentIdentifierKey")
public static let addedToDirectoryDateKey = URLResourceKey(rawValue: "NSURLAddedToDirectoryDateKey")
public static let quarantinePropertiesKey = URLResourceKey(rawValue: "NSURLQuarantinePropertiesKey")
public static let fileResourceTypeKey = URLResourceKey(rawValue: "NSURLFileResourceTypeKey")
public static let thumbnailDictionaryKey = URLResourceKey(rawValue: "NSURLThumbnailDictionaryKey")
public static let thumbnailKey = URLResourceKey(rawValue: "NSURLThumbnailKey")
public static let fileSizeKey = URLResourceKey(rawValue: "NSURLFileSizeKey")
public static let fileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLFileAllocatedSizeKey")
public static let totalFileSizeKey = URLResourceKey(rawValue: "NSURLTotalFileSizeKey")
public static let totalFileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLTotalFileAllocatedSizeKey")
public static let isAliasFileKey = URLResourceKey(rawValue: "NSURLIsAliasFileKey")
public static let volumeLocalizedFormatDescriptionKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedFormatDescriptionKey")
public static let volumeTotalCapacityKey = URLResourceKey(rawValue: "NSURLVolumeTotalCapacityKey")
public static let volumeAvailableCapacityKey = URLResourceKey(rawValue: "NSURLVolumeAvailableCapacityKey")
public static let volumeResourceCountKey = URLResourceKey(rawValue: "NSURLVolumeResourceCountKey")
public static let volumeSupportsPersistentIDsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsPersistentIDsKey")
public static let volumeSupportsSymbolicLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSymbolicLinksKey")
public static let volumeSupportsHardLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsHardLinksKey")
public static let volumeSupportsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsJournalingKey")
public static let volumeIsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeIsJournalingKey")
public static let volumeSupportsSparseFilesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSparseFilesKey")
public static let volumeSupportsZeroRunsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsZeroRunsKey")
public static let volumeSupportsCaseSensitiveNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCaseSensitiveNamesKey")
public static let volumeSupportsCasePreservedNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCasePreservedNamesKey")
public static let volumeSupportsRootDirectoryDatesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRootDirectoryDatesKey")
public static let volumeSupportsVolumeSizesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsVolumeSizesKey")
public static let volumeSupportsRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRenamingKey")
public static let volumeSupportsAdvisoryFileLockingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsAdvisoryFileLockingKey")
public static let volumeSupportsExtendedSecurityKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExtendedSecurityKey")
public static let volumeIsBrowsableKey = URLResourceKey(rawValue: "NSURLVolumeIsBrowsableKey")
public static let volumeMaximumFileSizeKey = URLResourceKey(rawValue: "NSURLVolumeMaximumFileSizeKey")
public static let volumeIsEjectableKey = URLResourceKey(rawValue: "NSURLVolumeIsEjectableKey")
public static let volumeIsRemovableKey = URLResourceKey(rawValue: "NSURLVolumeIsRemovableKey")
public static let volumeIsInternalKey = URLResourceKey(rawValue: "NSURLVolumeIsInternalKey")
public static let volumeIsAutomountedKey = URLResourceKey(rawValue: "NSURLVolumeIsAutomountedKey")
public static let volumeIsLocalKey = URLResourceKey(rawValue: "NSURLVolumeIsLocalKey")
public static let volumeIsReadOnlyKey = URLResourceKey(rawValue: "NSURLVolumeIsReadOnlyKey")
public static let volumeCreationDateKey = URLResourceKey(rawValue: "NSURLVolumeCreationDateKey")
public static let volumeURLForRemountingKey = URLResourceKey(rawValue: "NSURLVolumeURLForRemountingKey")
public static let volumeUUIDStringKey = URLResourceKey(rawValue: "NSURLVolumeUUIDStringKey")
public static let volumeNameKey = URLResourceKey(rawValue: "NSURLVolumeNameKey")
public static let volumeLocalizedNameKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedNameKey")
public static let volumeIsEncryptedKey = URLResourceKey(rawValue: "NSURLVolumeIsEncryptedKey")
public static let volumeIsRootFileSystemKey = URLResourceKey(rawValue: "NSURLVolumeIsRootFileSystemKey")
public static let volumeSupportsCompressionKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCompressionKey")
public static let volumeSupportsFileCloningKey = URLResourceKey(rawValue: "NSURLVolumeSupportsFileCloningKey")
public static let volumeSupportsSwapRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSwapRenamingKey")
public static let volumeSupportsExclusiveRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExclusiveRenamingKey")
public static let isUbiquitousItemKey = URLResourceKey(rawValue: "NSURLIsUbiquitousItemKey")
public static let ubiquitousItemHasUnresolvedConflictsKey = URLResourceKey(rawValue: "NSURLUbiquitousItemHasUnresolvedConflictsKey")
public static let ubiquitousItemIsDownloadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsDownloadingKey")
public static let ubiquitousItemIsUploadedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadedKey")
public static let ubiquitousItemIsUploadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadingKey")
public static let ubiquitousItemDownloadingStatusKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingStatusKey")
public static let ubiquitousItemDownloadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingErrorKey")
public static let ubiquitousItemUploadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemUploadingErrorKey")
public static let ubiquitousItemDownloadRequestedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadRequestedKey")
public static let ubiquitousItemContainerDisplayNameKey = URLResourceKey(rawValue: "NSURLUbiquitousItemContainerDisplayNameKey")
}
public struct URLFileResourceType : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
}
extension URLFileResourceType {
public static let namedPipe = URLFileResourceType(rawValue: "NSURLFileResourceTypeNamedPipe")
public static let characterSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeCharacterSpecial")
public static let directory = URLFileResourceType(rawValue: "NSURLFileResourceTypeDirectory")
public static let blockSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeBlockSpecial")
public static let regular = URLFileResourceType(rawValue: "NSURLFileResourceTypeRegular")
public static let symbolicLink = URLFileResourceType(rawValue: "NSURLFileResourceTypeSymbolicLink")
public static let socket = URLFileResourceType(rawValue: "NSURLFileResourceTypeSocket")
public static let unknown = URLFileResourceType(rawValue: "NSURLFileResourceTypeUnknown")
}
open class NSURL : NSObject, NSSecureCoding, NSCopying {
typealias CFType = CFURL
internal var _base = _CFInfo(typeID: CFURLGetTypeID())
internal var _flags : UInt32 = 0
internal var _encoding : CFStringEncoding = 0
internal var _string : UnsafeMutablePointer<CFString>? = nil
internal var _baseURL : UnsafeMutablePointer<CFURL>? = nil
internal var _extra : OpaquePointer? = nil
internal var _resourceInfo : OpaquePointer? = nil
internal var _range1 = NSRange(location: 0, length: 0)
internal var _range2 = NSRange(location: 0, length: 0)
internal var _range3 = NSRange(location: 0, length: 0)
internal var _range4 = NSRange(location: 0, length: 0)
internal var _range5 = NSRange(location: 0, length: 0)
internal var _range6 = NSRange(location: 0, length: 0)
internal var _range7 = NSRange(location: 0, length: 0)
internal var _range8 = NSRange(location: 0, length: 0)
internal var _range9 = NSRange(location: 0, length: 0)
internal var _cfObject : CFType {
if type(of: self) === NSURL.self {
return unsafeBitCast(self, to: CFType.self)
} else {
return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject)
}
}
var _resourceStorage: URLResourceValuesStorage? {
guard isFileURL else { return nil }
if let storage = _resourceStorageIfPresent {
return storage
} else {
let me = unsafeBitCast(self, to: CFURL.self)
let initial = URLResourceValuesStorage()
let result = _CFURLCopyResourceInfoInitializingAtomicallyIfNeeded(me, initial)
return Unmanaged<URLResourceValuesStorage>.fromOpaque(result).takeRetainedValue()
}
}
var _resourceStorageIfPresent: URLResourceValuesStorage? {
guard isFileURL else { return nil }
let me = unsafeBitCast(self, to: CFURL.self)
if let storage = _CFURLCopyResourceInfo(me) {
return Unmanaged<URLResourceValuesStorage>.fromOpaque(storage).takeRetainedValue()
} else {
return nil
}
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURL else { return false }
return CFEqual(_cfObject, other._cfObject)
}
open override var description: String {
if self.relativeString != self.absoluteString {
return "\(self.relativeString) -- \(self.baseURL!)"
} else {
return self.absoluteString
}
}
deinit {
_CFDeinit(self)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if isFileURL {
let newURL = CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject)!
if let storage = _resourceStorageIfPresent {
let newStorage = URLResourceValuesStorage(copying: storage)
_CFURLSetResourceInfo(newURL, newStorage)
}
return newURL._nsObject
} else {
return self
}
}
public static var supportsSecureCoding: Bool { return true }
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let base = aDecoder.decodeObject(of: NSURL.self, forKey:"NS.base")?._swiftObject
let relative = aDecoder.decodeObject(of: NSString.self, forKey:"NS.relative")
if relative == nil {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(relative!), relativeTo: base)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base")
aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative")
}
public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
super.init()
let thePath = _standardizedPath(path)
if thePath.length > 0 {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPlatformPathStyle, isDir, baseURL?._cfObject)
} else if let baseURL = baseURL {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, baseURL.path._cfObject, kCFURLPlatformPathStyle, baseURL.hasDirectoryPath, nil)
}
}
public convenience init(fileURLWithPath path: String, relativeTo baseURL: URL?) {
let thePath = _standardizedPath(path)
var isDir: ObjCBool = false
if validPathSeps.contains(where: { thePath.hasSuffix(String($0)) }) {
isDir = true
} else {
let absolutePath: String
if let absPath = baseURL?.appendingPathComponent(path).path {
absolutePath = absPath
} else {
absolutePath = path
}
let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir)
}
self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL)
}
public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) {
self.init(fileURLWithPath: path, isDirectory: isDir, relativeTo: nil)
}
public init(fileURLWithPath path: String) {
let thePath: String = _standardizedPath(path)
var isDir: ObjCBool = false
if validPathSeps.contains(where: { thePath.hasSuffix(String($0)) }) {
isDir = true
} else {
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
isDir = false
}
}
super.init()
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPlatformPathStyle, isDir.boolValue, nil)
}
public convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
let pathString = String(cString: path)
self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL)
}
public convenience init?(string URLString: String) {
self.init(string: URLString, relativeTo:nil)
}
public init?(string URLString: String, relativeTo baseURL: URL?) {
super.init()
if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) {
return nil
}
}
public init(dataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
// _CFURLInitWithURLString does not fail if checkForLegalCharacters == false
data.withUnsafeBytes { (rawBuffer: UnsafeRawBufferPointer) -> Void in
let ptr = rawBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else {
fatalError()
}
}
}
public init(absoluteURLWithDataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
data.withUnsafeBytes { (rawBuffer: UnsafeRawBufferPointer) -> Void in
let ptr = rawBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) {
return
}
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) {
return
}
fatalError()
}
}
/* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeTo:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding.
*/
open var dataRepresentation: Data {
let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0)
assert(bytesNeeded > 0)
let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded)
let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded)
if bytesFilled == bytesNeeded {
return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .free)
} else {
fatalError()
}
}
open var absoluteString: String {
if let absURL = CFURLCopyAbsoluteURL(_cfObject) {
return CFURLGetString(absURL)._swiftObject
}
return CFURLGetString(_cfObject)._swiftObject
}
// The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
open var relativeString: String {
return CFURLGetString(_cfObject)._swiftObject
}
open var baseURL: URL? {
return CFURLGetBaseURL(_cfObject)?._swiftObject
}
// if the receiver is itself absolute, this will return self.
open var absoluteURL: URL? {
return CFURLCopyAbsoluteURL(_cfObject)?._swiftObject
}
/* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier]
*/
open var scheme: String? {
return CFURLCopyScheme(_cfObject)?._swiftObject
}
internal var _isAbsolute : Bool {
return self.baseURL == nil && self.scheme != nil
}
open var resourceSpecifier: String? {
// Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme.
if !_isAbsolute {
return self.relativeString
} else {
let cf = _cfObject
guard CFURLCanBeDecomposed(cf) else {
return CFURLCopyResourceSpecifier(cf)?._swiftObject
}
guard baseURL == nil else {
return CFURLGetString(cf)?._swiftObject
}
let netLoc = CFURLCopyNetLocation(cf)?._swiftObject
let path = CFURLCopyPath(cf)?._swiftObject
let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject
if let netLoc = netLoc {
let p = path ?? ""
let rest = theRest ?? ""
return "//\(netLoc)\(p)\(rest)"
} else if let path = path {
let rest = theRest ?? ""
return "\(path)\(rest)"
} else {
return theRest
}
}
}
/* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL.
*/
open var host: String? {
return CFURLCopyHostName(_cfObject)?._swiftObject
}
open var port: NSNumber? {
let port = CFURLGetPortNumber(_cfObject)
if port == -1 {
return nil
} else {
return NSNumber(value: port)
}
}
open var user: String? {
return CFURLCopyUserName(_cfObject)?._swiftObject
}
open var password: String? {
let absoluteURL = CFURLCopyAbsoluteURL(_cfObject)
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .password, nil)
guard passwordRange.location != kCFNotFound else {
return nil
}
// For historical reasons, the password string should _not_ have its percent escapes removed.
let bufSize = CFURLGetBytes(absoluteURL, nil, 0)
let buf = [UInt8](unsafeUninitializedCapacity: bufSize) { buffer, initializedCount in
initializedCount = CFURLGetBytes(absoluteURL, buffer.baseAddress, buffer.count)
precondition(initializedCount == bufSize, "Inconsistency in CFURLGetBytes")
}
let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length]
return passwordBuf.withUnsafeBufferPointer { ptr in
NSString(bytes: ptr.baseAddress!, length: passwordBuf.count, encoding: String.Encoding.utf8.rawValue)?._swiftObject
}
}
open var path: String? {
let absURL = CFURLCopyAbsoluteURL(_cfObject)
guard var url = CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject else {
return nil
}
#if os(Windows)
// Per RFC 8089:E.2, if we have an absolute Windows/DOS path we can
// begin the URL with a drive letter rather than a `/`
let scalars = Array(url.unicodeScalars)
if isFileURL, url.isAbsolutePath,
scalars.count >= 3, scalars[0] == "/", scalars[2] == ":" {
url.removeFirst()
}
#endif
return url
}
open var fragment: String? {
return CFURLCopyFragment(_cfObject, nil)?._swiftObject
}
@available(swift, deprecated: 5.3, message: "The parameterString property is deprecated. When executing on Swift 5.3 or later, parameterString will always return nil, and the path method will return the complete path including the semicolon separator and params component if the URL string contains them.")
open var parameterString: String? {
return CFURLCopyParameterString(_cfObject, nil)?._swiftObject
}
open var query: String? {
return CFURLCopyQueryString(_cfObject, nil)?._swiftObject
}
// The same as path if baseURL is nil
open var relativePath: String? {
guard var url = CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject else {
return nil
}
#if os(Windows)
// Per RFC 8089:E.2, if we have an absolute Windows/DOS path we can
// begin the URL with a drive letter rather than a `/`
let scalars = Array(url.unicodeScalars)
if isFileURL, url.isAbsolutePath,
scalars.count >= 3, scalars[0] == "/", scalars[2] == ":" {
url.removeFirst()
}
#endif
return url
}
/* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to.
*/
open var hasDirectoryPath: Bool {
return CFURLHasDirectoryPath(_cfObject)
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding.
*/
open func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool {
return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) {
CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength)
}
}
#if os(Windows)
internal func _getWideFileSystemRepresentation(_ buffer: UnsafeMutablePointer<UInt16>, maxLength: Int) -> Bool {
_CFURLGetWideFileSystemRepresentation(_cfObject, true, buffer, maxLength)
}
#endif
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created.
*/
// Memory leak. See https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md
open var fileSystemRepresentation: UnsafePointer<Int8> {
#if os(Windows)
let bufSize = Int(MAX_PATH + 1)
#else
let bufSize = Int(PATH_MAX + 1)
#endif
let _fsrBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: bufSize)
_fsrBuffer.initialize(repeating: 0, count: bufSize)
if getFileSystemRepresentation(_fsrBuffer, maxLength: bufSize) {
return UnsafePointer(_fsrBuffer)
}
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is marked as non-nullable.
fatalError("URL cannot be expressed in the filesystem representation;" +
"use getFileSystemRepresentation to handle this case")
}
#if os(Windows)
internal var _wideFileSystemRepresentation: UnsafePointer<UInt16> {
let capacity: Int = Int(MAX_PATH) + 1
let buffer: UnsafeMutablePointer<UInt16> =
UnsafeMutablePointer<UInt16>.allocate(capacity: capacity)
buffer.initialize(repeating: 0, count: capacity)
if _getWideFileSystemRepresentation(buffer, maxLength: capacity) {
return UnsafePointer(buffer)
}
fatalError("URL cannot be expressed in the filesystem representation; use getFileSystemRepresentation to handle this case")
}
#endif
// Whether the scheme is file:; if myURL.isFileURL is true, then myURL.path is suitable for input into FileManager or NSPathUtilities.
open var isFileURL: Bool {
return _CFURLIsFileURL(_cfObject)
}
/* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */
open var standardized: URL? {
guard path != nil else {
return nil
}
guard let components = NSURLComponents(string: relativeString), let componentPath = components.path else {
return nil
}
if componentPath.contains("..") || componentPath.contains(".") {
components.path = _pathByRemovingDots(pathComponents!)
}
if let filePath = components.path, isFileURL {
return URL(fileURLWithPath: filePath, isDirectory: hasDirectoryPath, relativeTo: baseURL)
}
return components.url(relativeTo: baseURL)
}
/* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
// TODO: should be `checkResourceIsReachableAndReturnError` with autoreleased error parameter.
// Currently Autoreleased pointers is not supported on Linux.
open func checkResourceIsReachable() throws -> Bool {
guard isFileURL,
let path = path else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadUnsupportedScheme.rawValue)
}
guard FileManager.default.fileExists(atPath: path) else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadNoSuchFile.rawValue,
userInfo: [
"NSURL" : self,
"NSFilePath" : path])
}
return true
}
/* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation.
*/
open var filePathURL: URL? {
guard isFileURL else {
return nil
}
return URL(string: absoluteString)
}
override open var _cfTypeID: CFTypeID {
return CFURLGetTypeID()
}
open func removeAllCachedResourceValues() {
_resourceStorage?.removeAllCachedResourceValues()
}
open func removeCachedResourceValue(forKey key: URLResourceKey) {
_resourceStorage?.removeCachedResourceValue(forKey: key)
}
open func getResourceValue(_ value: inout AnyObject?, forKey key: URLResourceKey) throws {
guard let storage = _resourceStorage else { value = nil; return }
try storage.getResourceValue(&value, forKey: key, url: self)
}
open func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : Any] {
guard let storage = _resourceStorage else { return [:] }
return try storage.resourceValues(forKeys: keys, url: self)
}
open func setResourceValue(_ value: Any?, forKey key: URLResourceKey) throws {
guard let storage = _resourceStorage else { return }
try storage.setResourceValue(value, forKey: key, url: self)
}
open func setResourceValues(_ keyedValues: [URLResourceKey : Any]) throws {
guard let storage = _resourceStorage else { return }
try storage.setResourceValues(keyedValues, url: self)
}
open func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) {
guard let storage = _resourceStorage else { return }
storage.setTemporaryResourceValue(value, forKey: key)
}
}
internal class URLResourceValuesStorage: NSObject {
let valuesCacheLock = NSLock()
var valuesCache: [URLResourceKey: Any] = [:]
func removeAllCachedResourceValues() {
valuesCacheLock.lock()
defer { valuesCacheLock.unlock() }
valuesCache = [:]
}
func removeCachedResourceValue(forKey key: URLResourceKey) {
valuesCacheLock.lock()
defer { valuesCacheLock.unlock() }
valuesCache.removeValue(forKey: key)
}
func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) {
valuesCacheLock.lock()
defer { valuesCacheLock.unlock() }
if let value = value {
valuesCache[key] = value
} else {
valuesCache.removeValue(forKey: key)
}
}
func getResourceValue(_ value: inout AnyObject?,
forKey key: URLResourceKey, url: NSURL) throws {
let cached = valuesCacheLock.synchronized {
return valuesCache[key]
}
if let cached = cached {
value = __SwiftValue.store(cached)
return
}
let fetchedValues = try read([key], for: url)
if let fetched = fetchedValues[key] {
valuesCacheLock.synchronized {
valuesCache[key] = fetched
}
value = __SwiftValue.store(fetched)
} else {
value = nil
}
}
func resourceValues(forKeys keys: [URLResourceKey], url: NSURL) throws -> [URLResourceKey : Any] {
var result: [URLResourceKey : Any] = [:]
var keysToFetch: [URLResourceKey] = []
valuesCacheLock.synchronized {
for key in keys {
if let value = valuesCache[key] {
result[key] = value
} else {
keysToFetch.append(key)
}
}
}
if keysToFetch.count > 0 {
let found = try read(keysToFetch, for: url).compactMapValues { $0 }
valuesCacheLock.synchronized {
valuesCache.merge(found, uniquingKeysWith: { $1 })
}
result.merge(found, uniquingKeysWith: { $1 })
}
return result
}
func setResourceValue(_ value: Any?, forKey key: URLResourceKey, url: NSURL) throws {
try write([key: value], to: url)
valuesCacheLock.lock()
defer { valuesCacheLock.unlock() }
valuesCache[key] = value
}
func setResourceValues(_ keyedValues: [URLResourceKey : Any], url: NSURL) throws {
try write(keyedValues, to: url)
valuesCacheLock.lock()
defer { valuesCacheLock.unlock() }
valuesCache.merge(keyedValues, uniquingKeysWith: { $1 })
}
internal override init() {
super.init()
}
internal init(copying storage: URLResourceValuesStorage) {
storage.valuesCacheLock.lock()
defer { storage.valuesCacheLock.unlock() }
valuesCache = storage.valuesCache
super.init()
}
}
extension NSCharacterSet {
// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
// Returns a character set containing the characters allowed in an URL's user subcomponent.
open class var urlUserAllowed: CharacterSet {
return _CFURLComponentsGetURLUserAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's password subcomponent.
open class var urlPasswordAllowed: CharacterSet {
return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's host subcomponent.
open class var urlHostAllowed: CharacterSet {
return _CFURLComponentsGetURLHostAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet).
open class var urlPathAllowed: CharacterSet {
return _CFURLComponentsGetURLPathAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's query component.
open class var urlQueryAllowed: CharacterSet {
return _CFURLComponentsGetURLQueryAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's fragment component.
open class var urlFragmentAllowed: CharacterSet {
return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._swiftObject
}
}
extension NSString {
// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
open func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject
}
// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
open var removingPercentEncoding: String? {
return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)?._swiftObject
}
}
extension NSURL {
/* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do.
*/
open class func fileURL(withPathComponents components: [String]) -> URL? {
let path = NSString.path(withComponents: components)
if components.last == "/" {
return URL(fileURLWithPath: path, isDirectory: true)
} else {
return URL(fileURLWithPath: path)
}
}
internal func _pathByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String? {
guard let p = path else {
return nil
}
if p == "/" {
return p
}
var result = p
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if result[curPos] == "/" {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && result.hasSuffix("/") {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
open var pathComponents: [String]? {
return _pathComponents(path)
}
open var lastPathComponent: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return fixedSelf
}
return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent))
}
open var pathExtension: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return ""
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.suffix(from: extensionPos))
} else {
return ""
}
}
open func appendingPathComponent(_ pathComponent: String) -> URL? {
var result : URL? = appendingPathComponent(pathComponent, isDirectory: false)
// Since we are appending to a URL, path seperators should
// always be '/', even if we're on Windows
if !pathComponent.hasSuffix("/") && isFileURL {
if let urlWithoutDirectory = result {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: urlWithoutDirectory.path, isDirectory: &isDir) && isDir.boolValue {
result = self.appendingPathComponent(pathComponent, isDirectory: true)
}
}
}
return result
}
open func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? {
return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._swiftObject
}
open var deletingLastPathComponent: URL? {
return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
open func appendingPathExtension(_ pathExtension: String) -> URL? {
return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._swiftObject
}
open var deletingPathExtension: URL? {
return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
/* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged.
*/
open var standardizingPath: URL? {
// Documentation says it should expand initial tilde, but it does't do this on OS X.
// In remaining cases it works just like URLByResolvingSymlinksInPath.
return _resolveSymlinksInPath(excludeSystemDirs: true, preserveDirectoryFlag: true)
}
open var resolvingSymlinksInPath: URL? {
return _resolveSymlinksInPath(excludeSystemDirs: true)
}
internal func _resolveSymlinksInPath(excludeSystemDirs: Bool, preserveDirectoryFlag: Bool = false) -> URL? {
guard isFileURL else {
return URL(string: absoluteString)
}
guard let selfPath = path else {
return URL(string: absoluteString)
}
let absolutePath: String
if selfPath.isAbsolutePath {
absolutePath = selfPath
} else {
let workingDir = FileManager.default.currentDirectoryPath
absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath)
}
var components = URL(fileURLWithPath: absolutePath).pathComponents
guard !components.isEmpty else {
return URL(string: absoluteString)
}
var resolvedPath = components.removeFirst()
for component in components {
switch component {
case "", ".":
break
case "..":
resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent
default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
}
}
// It might be a responsibility of NSURL(fileURLWithPath:). Check it.
var isExistingDirectory: ObjCBool = false
let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory)
if excludeSystemDirs {
resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath
}
if isExistingDirectory.boolValue && !resolvedPath.hasSuffix("/") {
resolvedPath += "/"
}
if preserveDirectoryFlag {
return URL(fileURLWithPath: resolvedPath, isDirectory: self.hasDirectoryPath)
} else {
return URL(fileURLWithPath: resolvedPath)
}
}
fileprivate func _pathByRemovingDots(_ comps: [String]) -> String {
var components = comps
if(components.last == "/") {
components.removeLast()
}
guard !components.isEmpty else {
return self.path!
}
let isAbsolutePath = components.first == "/"
var result : String = components.removeFirst()
for component in components {
switch component {
case ".":
break
case ".." where isAbsolutePath:
result = result._bridgeToObjectiveC().deletingLastPathComponent
default:
result = result._bridgeToObjectiveC().appendingPathComponent(component)
}
}
if(self.path!.hasSuffix("/")) {
result += "/"
}
return result
}
}
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying {
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
open private(set) var name: String
open private(set) var value: String?
}
open class NSURLComponents: NSObject, NSCopying {
private let _components : CFURLComponents!
open override func copy() -> Any {
return copy(with: nil)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLComponents else { return false }
return self === other
|| (scheme == other.scheme
&& user == other.user
&& password == other.password
&& host == other.host
&& port == other.port
&& path == other.path
&& query == other.query
&& fragment == other.fragment)
}
open override var hash: Int {
var hasher = Hasher()
hasher.combine(scheme)
hasher.combine(user)
hasher.combine(password)
hasher.combine(host)
hasher.combine(port)
hasher.combine(path)
hasher.combine(query)
hasher.combine(fragment)
return hasher.finalize()
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSURLComponents()
copy.scheme = self.scheme
copy.user = self.user
copy.password = self.password
copy.host = self.host
copy.port = self.port
copy.path = self.path
copy.query = self.query
copy.fragment = self.fragment
return copy
}
// Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned.
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {
_components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve)
super.init()
if _components == nil {
return nil
}
}
// Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.
public init?(string URLString: String) {
_components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject)
super.init()
if _components == nil {
return nil
}
}
public override init() {
_components = _CFURLComponentsCreate(kCFAllocatorSystemDefault)
}
// Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var url: URL? {
guard let result = _CFURLComponentsCopyURL(_components) else { return nil }
return unsafeBitCast(result, to: URL.self)
}
// Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open func url(relativeTo baseURL: URL?) -> URL? {
if let componentString = string {
return URL(string: componentString, relativeTo: baseURL)
}
return nil
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var string: String? {
return _CFURLComponentsCopyString(_components)?._swiftObject
}
// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
// Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
// Attempting to set the scheme with an invalid scheme string will cause an exception.
open var scheme: String? {
get {
return _CFURLComponentsCopyScheme(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetScheme(_components, new?._cfObject) {
fatalError()
}
}
}
open var user: String? {
get {
return _CFURLComponentsCopyUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var password: String? {
get {
return _CFURLComponentsCopyPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var host: String? {
get {
return _CFURLComponentsCopyHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetHost(_components, new?._cfObject) {
fatalError()
}
}
}
// Attempting to set a negative port number will cause an exception.
open var port: NSNumber? {
get {
if let result = _CFURLComponentsCopyPort(_components) {
return unsafeBitCast(result, to: NSNumber.self)
} else {
return nil
}
}
set(new) {
if !_CFURLComponentsSetPort(_components, new?._cfObject) {
fatalError()
}
}
}
open var path: String? {
get {
return _CFURLComponentsCopyPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var query: String? {
get {
return _CFURLComponentsCopyQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var fragment: String? {
get {
return _CFURLComponentsCopyFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetFragment(_components, new?._cfObject) {
fatalError()
}
}
}
// Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the urlPathAllowed).
open var percentEncodedUser: String? {
get {
return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPassword: String? {
get {
return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedHost: String? {
get {
return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPath: String? {
get {
return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedQuery: String? {
get {
return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedFragment: String? {
get {
return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) {
fatalError()
}
}
}
/* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
*/
open var rangeOfScheme: NSRange {
return NSRange(_CFURLComponentsGetRangeOfScheme(_components))
}
open var rangeOfUser: NSRange {
return NSRange(_CFURLComponentsGetRangeOfUser(_components))
}
open var rangeOfPassword: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPassword(_components))
}
open var rangeOfHost: NSRange {
return NSRange(_CFURLComponentsGetRangeOfHost(_components))
}
open var rangeOfPort: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPort(_components))
}
open var rangeOfPath: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPath(_components))
}
open var rangeOfQuery: NSRange {
return NSRange(_CFURLComponentsGetRangeOfQuery(_components))
}
open var rangeOfFragment: NSRange {
return NSRange(_CFURLComponentsGetRangeOfFragment(_components))
}
// The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil.
// The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object.
// Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
open var queryItems: [URLQueryItem]? {
get {
// This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value
guard let queryArray = _CFURLComponentsCopyQueryItems(_components) else {
return nil
}
let count = CFArrayGetCount(queryArray)
return (0..<count).map { idx in
let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), to: NSDictionary.self)
let swiftEntry = oneEntry._swiftObject
let entryName = swiftEntry["name"] as! String
let entryValue = swiftEntry["value"] as? String
return URLQueryItem(name: entryName, value: entryValue)
}
}
set(new) {
guard let new = new else {
self.percentEncodedQuery = nil
return
}
// The CFURL implementation requires two CFArrays, one for names and one for values
var names = [CFTypeRef]()
var values = [CFTypeRef]()
for entry in new {
names.append(entry.name._cfObject)
if let v = entry.value {
values.append(v._cfObject)
} else {
values.append(kCFNull)
}
}
_CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject)
}
}
}
extension NSURL: _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = URL
internal var _swiftObject: SwiftType { return URL(reference: self) }
}
extension CFURL : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSURL
typealias SwiftType = URL
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: SwiftType { return _nsObject._swiftObject }
}
extension URL : _NSBridgeable, _CFBridgeable {
typealias NSType = NSURL
typealias CFType = CFURL
internal var _nsObject: NSType { return self.reference }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
extension NSURL : _StructTypeBridgeable {
public typealias _StructType = URL
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLComponents : _StructTypeBridgeable {
public typealias _StructType = URLComponents
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLQueryItem : _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
// -----
internal func _CFSwiftURLCopyResourcePropertyForKey(_ url: CFTypeRef, _ key: CFString, _ valuePointer: UnsafeMutablePointer<Unmanaged<CFTypeRef>?>?, _ errorPointer: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> _DarwinCompatibleBoolean {
do {
let key = URLResourceKey(rawValue: key._swiftObject)
let values = try unsafeBitCast(url, to: NSURL.self).resourceValues(forKeys: [ key ])
let value = values[key]
if let value = value {
let result = __SwiftValue.store(value)
valuePointer?.pointee = .passRetained(unsafeBitCast(result, to: CFTypeRef.self))
} else {
valuePointer?.pointee = nil
}
return true
} catch {
if let errorPointer = errorPointer {
let nsError = (error as? NSError) ?? NSError(domain: NSCocoaErrorDomain, code: CocoaError.featureUnsupported.rawValue)
let cfError = Unmanaged.passRetained(nsError._cfObject)
errorPointer.pointee = cfError
}
return false
}
}
internal func _CFSwiftURLCopyResourcePropertiesForKeys(_ url: CFTypeRef, _ keys: CFArray, _ errorPointer: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Unmanaged<CFDictionary>? {
do {
var swiftKeys: [URLResourceKey] = []
for nsKey in keys._swiftObject {
if let stringKey = nsKey as? String {
swiftKeys.append(URLResourceKey(rawValue: stringKey))
}
}
let result = try unsafeBitCast(url, to: NSURL.self).resourceValues(forKeys: swiftKeys)
let finalDictionary = NSMutableDictionary()
for entry in result {
finalDictionary[entry.key.rawValue._nsObject] = entry.value
}
return .passRetained(finalDictionary._cfObject)
} catch {
if let errorPointer = errorPointer {
let nsError = (error as? NSError) ?? NSError(domain: NSCocoaErrorDomain, code: CocoaError.featureUnsupported.rawValue)
let cfError = Unmanaged.passRetained(nsError._cfObject)
errorPointer.pointee = cfError
}
return nil
}
}
internal func _CFSwiftURLSetResourcePropertyForKey(_ url: CFTypeRef, _ key: CFString, _ value: CFTypeRef?, _ errorPointer: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> _DarwinCompatibleBoolean {
do {
let key = URLResourceKey(rawValue: key._swiftObject)
try unsafeBitCast(url, to: NSURL.self).setResourceValue(__SwiftValue.fetch(value), forKey: key)
return true
} catch {
if let errorPointer = errorPointer {
let nsError = (error as? NSError) ?? NSError(domain: NSCocoaErrorDomain, code: CocoaError.featureUnsupported.rawValue)
let cfError = Unmanaged.passRetained(nsError._cfObject)
errorPointer.pointee = cfError
}
return false
}
}
internal func _CFSwiftURLSetResourcePropertiesForKeys(_ url: CFTypeRef, _ properties: CFDictionary, _ errorPointer: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> _DarwinCompatibleBoolean {
do {
var swiftValues: [URLResourceKey: Any] = [:]
let swiftProperties = properties._swiftObject
for entry in swiftProperties {
if let stringKey = entry.key as? String {
swiftValues[URLResourceKey(rawValue: stringKey)] = entry.value
}
}
try unsafeBitCast(url, to: NSURL.self).setResourceValues(swiftValues)
return true
} catch {
if let errorPointer = errorPointer {
let nsError = (error as? NSError) ?? NSError(domain: NSCocoaErrorDomain, code: CocoaError.featureUnsupported.rawValue)
let cfError = Unmanaged.passRetained(nsError._cfObject)
errorPointer.pointee = cfError
}
return false
}
}
internal func _CFSwiftURLClearResourcePropertyCacheForKey(_ url: CFTypeRef, _ key: CFString) {
let swiftKey = URLResourceKey(rawValue: key._swiftObject)
unsafeBitCast(url, to: NSURL.self).removeCachedResourceValue(forKey: swiftKey)
}
internal func _CFSwiftURLClearResourcePropertyCache(_ url: CFTypeRef) {
unsafeBitCast(url, to: NSURL.self).removeAllCachedResourceValues()
}
internal func _CFSwiftSetTemporaryResourceValueForKey(_ url: CFTypeRef, _ key: CFString, _ value: CFTypeRef) {
unsafeBitCast(url, to: NSURL.self).setTemporaryResourceValue(__SwiftValue.fetch(value), forKey: URLResourceKey(rawValue: key._swiftObject))
}
internal func _CFSwiftURLResourceIsReachable(_ url: CFTypeRef, _ errorPointer: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> _DarwinCompatibleBoolean {
do {
let reachable = try unsafeBitCast(url, to: NSURL.self).checkResourceIsReachable()
return reachable ? true : false
} catch {
if let errorPointer = errorPointer {
let nsError = (error as? NSError) ?? NSError(domain: NSCocoaErrorDomain, code: CocoaError.featureUnsupported.rawValue)
let cfError = Unmanaged.passRetained(nsError._cfObject)
errorPointer.pointee = cfError
}
return false
}
}
// MARK: Fetching URL resource values
internal class _URLFileResourceIdentifier: NSObject {
let path: String
let inode: Int
let volumeIdentifier: Int
init(path: String, inode: Int, volumeIdentifier: Int) {
self.path = path
self.inode = inode
self.volumeIdentifier = volumeIdentifier
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? _URLFileResourceIdentifier else {
return false
}
return path == other.path || (inode == other.inode && volumeIdentifier == other.volumeIdentifier)
}
override var hash: Int {
return path._nsObject.hashValue ^ inode ^ volumeIdentifier
}
}
fileprivate extension URLResourceValuesStorage {
func read(_ keys: [URLResourceKey], for url: NSURL) throws -> [URLResourceKey: Any?] {
var result: [URLResourceKey: Any?] = [:]
let fm = FileManager.default
let path = url.path ?? ""
// Memoized access to attributes:
var fileAttributesStorage: [FileAttributeKey: Any]? = nil
func attributes() throws -> [FileAttributeKey: Any] {
if let storage = fileAttributesStorage {
return storage
} else {
let storage = try fm._attributesOfItem(atPath: path, includingPrivateAttributes: true)
fileAttributesStorage = storage
return storage
}
}
func attribute(_ fileAttributeKey: FileAttributeKey) throws -> Any? {
let attributeValues = try attributes()
return attributeValues[fileAttributeKey]
}
// Memoized access to lstat:
var urlStatStorage: stat?
func urlStat() throws -> stat {
if let storage = urlStatStorage {
return storage
} else {
let storage = try fm._lstatFile(atPath: path)
urlStatStorage = storage
return storage
}
}
// Memoized access to volume URLs:
var volumeURLsStorage: [URL]?
var volumeURLs: [URL] {
if let storage = volumeURLsStorage {
return storage
} else {
let storage = fm.mountedVolumeURLs(includingResourceValuesForKeys: nil) ?? []
volumeURLsStorage = storage
return storage
}
}
var volumeAttributesStorage: [FileAttributeKey: Any]?
var blockSizeStorage: UInt64?
func volumeAttributes() throws -> [FileAttributeKey: Any] {
if let storage = volumeAttributesStorage {
return storage
} else {
let (storage, block) = try fm._attributesOfFileSystemIncludingBlockSize(forPath: path)
volumeAttributesStorage = storage
blockSizeStorage = block
return storage
}
}
func blockSize() throws -> UInt64? {
_ = try volumeAttributes()
return blockSizeStorage
}
func volumeAttribute(_ fileAttributeKey: FileAttributeKey) throws -> Any? {
let attributeValues = try volumeAttributes()
return attributeValues[fileAttributeKey]
}
var volumeURLStorage: (searched: Bool, url: URL?)?
func volumeURL() throws -> URL? {
if let url = volumeURLStorage {
return url.url
}
var foundURL: URL?
for volumeURL in volumeURLs {
var relationship: FileManager.URLRelationship = .other
try fm.getRelationship(&relationship, ofDirectoryAt: volumeURL, toItemAt: url._swiftObject)
if relationship == .same || relationship == .contains {
foundURL = volumeURL
break
}
}
volumeURLStorage = (searched: true, url: foundURL)
return foundURL
}
for key in keys {
switch key {
case .nameKey:
result[key] = url.lastPathComponent
case .localizedNameKey:
result[key] = fm.displayName(atPath: path)
case .isRegularFileKey:
result[key] = try attribute(.type) as? FileAttributeType == FileAttributeType.typeRegular
case .isDirectoryKey:
result[key] = try attribute(.type) as? FileAttributeType == FileAttributeType.typeDirectory
case .isSymbolicLinkKey:
result[key] = try attribute(.type) as? FileAttributeType == FileAttributeType.typeSymbolicLink
case .isVolumeKey:
result[key] = volumeURLs.contains(url._swiftObject)
case .isPackageKey:
result[key] = try attribute(.type) as? FileAttributeType == FileAttributeType.typeDirectory && url.pathExtension != nil && url.pathExtension != ""
case .isApplicationKey:
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
result[key] = try attribute(.type) as? FileAttributeType == FileAttributeType.typeDirectory && url.pathExtension == "app"
#else
result[key] = false
#endif
case .applicationIsScriptableKey:
// Not supported.
break
case .isSystemImmutableKey:
result[key] = try attribute(._systemImmutable) as? Bool == true
case .isUserImmutableKey:
result[key] = try attribute(._userImmutable) as? Bool == true
case .isHiddenKey:
result[key] = try attribute(._hidden) as? Bool == true
case .hasHiddenExtensionKey:
result[key] = false // Most OSes do not have a way to record this.
case .creationDateKey:
result[key] = try attribute(.creationDate)
case .contentAccessDateKey:
result[key] = try attribute(._accessDate)
case .contentModificationDateKey:
result[key] = try attribute(.modificationDate)
case .attributeModificationDateKey:
// We do not support this in a cross-platform manner.
break
case .linkCountKey:
result[key] = Int(try urlStat().st_nlink)
case .parentDirectoryURLKey:
result[key] = url.deletingLastPathComponent
case .volumeURLKey:
result[key] = try volumeURL()
case .fileResourceIdentifierKey:
result[key] = _URLFileResourceIdentifier(path: path, inode: Int(try urlStat().st_ino), volumeIdentifier: Int(try urlStat().st_dev))
case .volumeIdentifierKey:
result[key] = try volumeAttribute(.systemNumber)
case .preferredIOBlockSizeKey:
result[key] = try blockSize()
case .isReadableKey:
result[key] = fm.isReadableFile(atPath: path)
case .isWritableKey:
result[key] = fm.isWritableFile(atPath: path)
case .isExecutableKey:
result[key] = fm.isExecutableFile(atPath: path)
case .pathKey:
result[key] = url.path
case .canonicalPathKey:
result[key] = try fm._canonicalizedPath(toFileAtPath: path)
case .fileResourceTypeKey:
result[key] = try attribute(.type)
case .totalFileSizeKey: fallthrough // FIXME: This should add the size of any metadata.
case .fileSizeKey:
result[key] = try attribute(.size)
case .totalFileAllocatedSizeKey: fallthrough // FIXME: This should add the size of any metadata.
case .fileAllocatedSizeKey:
#if !os(Windows)
let stat = try urlStat()
result[key] = Int(stat.st_blocks) * Int(stat.st_blksize)
#endif
case .isAliasFileKey:
// swift-corelibs-foundation does not support aliases and bookmarks.
break
case .volumeLocalizedFormatDescriptionKey:
// FIXME: This should have different names for different kinds of volumes, and be localized.
result[key] = "Volume"
case .volumeTotalCapacityKey:
result[key] = try volumeAttribute(.systemSize)
case .volumeAvailableCapacityKey:
result[key] = try volumeAttribute(.systemFreeSize)
case .volumeResourceCountKey:
result[key] = try volumeAttribute(.systemFileNumber)
// FIXME: swift-corelibs-foundation does not currently support querying this kind of filesystem information. We return reasonable assumptions for now, with the understanding that by noting support we are encouraging the application to try performing corresponding I/O operations (and handle those errors, which they already must) instead. Where those keys would inform I/O decisions that are not single operations, we assume conservatively.
case .volumeSupportsPersistentIDsKey:
result[key] = false
case .volumeSupportsSymbolicLinksKey:
result[key] = true
case .volumeSupportsHardLinksKey:
result[key] = true
case .volumeSupportsJournalingKey:
result[key] = false
case .volumeIsJournalingKey:
result[key] = false
case .volumeSupportsSparseFilesKey:
result[key] = false
case .volumeSupportsZeroRunsKey:
result[key] = false
case .volumeSupportsRootDirectoryDatesKey:
result[key] = true
case .volumeSupportsVolumeSizesKey:
result[key] = true
case .volumeSupportsRenamingKey:
result[key] = true
case .volumeSupportsAdvisoryFileLockingKey:
result[key] = false
case .volumeSupportsExtendedSecurityKey:
result[key] = false
case .volumeIsBrowsableKey:
result[key] = true
case .volumeIsReadOnlyKey:
result[key] = false
case .volumeCreationDateKey:
result[key] = try volumeAttribute(.creationDate)
case .volumeURLForRemountingKey:
result[key] = nil
case .volumeMaximumFileSizeKey: fallthrough
case .volumeIsEjectableKey: fallthrough
case .volumeIsRemovableKey: fallthrough
case .volumeIsInternalKey: fallthrough
case .volumeIsAutomountedKey: fallthrough
case .volumeIsLocalKey: fallthrough
case .volumeSupportsCaseSensitiveNamesKey: fallthrough
case .volumeUUIDStringKey: fallthrough
case .volumeIsEncryptedKey: fallthrough
case .volumeSupportsCompressionKey: fallthrough
case .volumeSupportsFileCloningKey: fallthrough
case .volumeSupportsSwapRenamingKey: fallthrough
case .volumeSupportsExclusiveRenamingKey: fallthrough
case .volumeSupportsCasePreservedNamesKey:
// Whatever we assume here, we may make problems for the implementation that relies on them; we just don't answer for now.
break
case .volumeNameKey:
if let url = try volumeURL() {
result[key] = url.lastPathComponent
}
case .volumeLocalizedNameKey:
if let url = try volumeURL() {
result[key] = fm.displayName(atPath: url.path)
}
case .volumeIsRootFileSystemKey:
#if !os(Windows)
if let url = try volumeURL() {
result[key] = url.path == "/"
}
#endif
case .isUbiquitousItemKey: fallthrough
case .ubiquitousItemHasUnresolvedConflictsKey: fallthrough
case .ubiquitousItemIsDownloadingKey: fallthrough
case .ubiquitousItemIsUploadedKey: fallthrough
case .ubiquitousItemIsUploadingKey: fallthrough
case .ubiquitousItemDownloadingStatusKey: fallthrough
case .ubiquitousItemDownloadingErrorKey: fallthrough
case .ubiquitousItemUploadingErrorKey: fallthrough
case .ubiquitousItemDownloadRequestedKey: fallthrough
case .ubiquitousItemContainerDisplayNameKey: fallthrough
case .fileSecurityKey: fallthrough
case .isExcludedFromBackupKey: fallthrough
case .tagNamesKey: fallthrough
case .typeIdentifierKey: fallthrough
case .localizedTypeDescriptionKey: fallthrough
case .labelNumberKey: fallthrough
case .labelColorKey: fallthrough
case .localizedLabelKey: fallthrough
case .effectiveIconKey: fallthrough
case .isMountTriggerKey: fallthrough
case .generationIdentifierKey: fallthrough
case .documentIdentifierKey: fallthrough
case .addedToDirectoryDateKey: fallthrough
case .quarantinePropertiesKey: fallthrough
case .thumbnailDictionaryKey: fallthrough
case .thumbnailKey: fallthrough
case .customIconKey:
// Not supported outside of Apple OSes.
break
default:
break
}
}
return result
}
func write(_ keysAndValues: [URLResourceKey: Any?], to url: NSURL) throws {
// Keys we could support but don't yet (FIXME):
// .labelNumberKey, // Darwin only:
// .fileSecurityKey,
// .isExcludedFromBackupKey,
// .tagNamesKey,
// .quarantinePropertiesKey,
// .addedToDirectoryDateKey, // Most OSes do not have a separate stat()-able added-to-directory date.
// .volumeNameKey, // The way to set this is very system-dependent.
var finalError: Error?
var unsuccessfulKeys = Set(keysAndValues.keys)
let fm = FileManager.default
let path = url.path ?? ""
let swiftURL = url._swiftObject
var attributesToSet: [FileAttributeKey: Any] = [:]
var keysThatSucceedBySettingAttributes: Set<URLResourceKey> = []
for key in keysAndValues.keys {
let value = keysAndValues[key]
do {
var succeeded = true
func prepareToSetFileAttribute(_ attributeKey: FileAttributeKey, value: Any?) throws {
if let value = value {
attributesToSet[attributeKey] = value
keysThatSucceedBySettingAttributes.insert(key)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue)
}
succeeded = false
}
switch key {
case .isUserImmutableKey:
try prepareToSetFileAttribute(._userImmutable, value: value as? Bool)
case .isSystemImmutableKey:
try prepareToSetFileAttribute(._systemImmutable, value: value as? Bool)
case .hasHiddenExtensionKey:
try prepareToSetFileAttribute(.extensionHidden, value: value as? Bool)
case .creationDateKey:
try prepareToSetFileAttribute(.creationDate, value: value as? Date)
case .contentAccessDateKey:
try prepareToSetFileAttribute(._accessDate, value: value as? Date)
case .contentModificationDateKey:
try prepareToSetFileAttribute(.modificationDate, value: value as? Date)
case .isHiddenKey:
try prepareToSetFileAttribute(._hidden, value: value as? Bool)
default:
/* https://developer.apple.com/documentation/foundation/nsurl/1408208-setresourcevalues:
Attempts to set a read-only resource property or to set a resource property that is not supported by the resource are ignored and are not considered errors.
Properties swift-corelibs-foundation doesn't support are treated as if they are supported by no resource. */
break
}
if succeeded {
unsuccessfulKeys.remove(key)
}
} catch {
finalError = error
break
}
// _setAttributes(…) needs to figure out the correct order to apply these attributes in, so set them all together at the end.
if !attributesToSet.isEmpty {
try fm._setAttributes(attributesToSet, ofItemAtPath: path, includingPrivateAttributes: true)
unsuccessfulKeys.formSymmetricDifference(keysThatSucceedBySettingAttributes)
}
// The name must be set last, since otherwise the URL may be invalid.
if keysAndValues.keys.contains(.nameKey) {
if let value = keysAndValues[.nameKey] as? String {
let destination = swiftURL.deletingLastPathComponent().appendingPathComponent(value)
try fm.moveItem(at: swiftURL, to: destination)
unsuccessfulKeys.remove(.nameKey)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInvalidFileName.rawValue)
}
}
}
if let finalError = finalError {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [
URLResourceKey.keysOfUnsetValuesKey.rawValue: Array(unsuccessfulKeys),
NSUnderlyingErrorKey: finalError,
])
}
}
}
// -----
internal extension Date {
#if !os(Windows)
init(timespec: timespec) {
self.init(timeIntervalSince1970: TimeInterval(timespec.tv_sec), nanoseconds: Double(timespec.tv_nsec))
}
#endif
init(timeIntervalSince1970: TimeInterval, nanoseconds: Double = 0) {
self.init(timeIntervalSinceReferenceDate: (timeIntervalSince1970 - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * nanoseconds))
}
}
extension stat {
var lastModificationDate: Date {
#if canImport(Darwin)
return Date(timespec: st_mtimespec)
#elseif os(Windows)
return Date(timeIntervalSince1970: TimeInterval(st_mtime))
#else
return Date(timespec: st_mtim)
#endif
}
var lastAccessDate: Date {
#if canImport(Darwin)
return Date(timespec: st_atimespec)
#elseif os(Windows)
return Date(timeIntervalSince1970: TimeInterval(st_atime))
#else
return Date(timespec: st_atim)
#endif
}
var creationDate: Date {
#if canImport(Darwin)
return Date(timespec: st_birthtimespec)
#elseif os(Windows)
return Date(timeIntervalSince1970: TimeInterval(st_ctime))
#else
return Date(timespec: st_ctim)
#endif
}
}
| 43.845137 | 740 | 0.653558 |
5d352f7e2e5eb51218140399a47874e54b8deb33 | 1,237 | import Combine
import Foundation
let subject_example1 = PassthroughSubject<Int, Never>()
let subject_example2 = PassthroughSubject<Int, Never>()
check("Subject Order") {
subject_example1.merge(with: subject_example2)
}
subject_example1.send(20)
subject_example2.send(1)
subject_example1.send(40)
subject_example1.send(60)
subject_example2.send(1)
subject_example1.send(80)
subject_example1.send(100)
subject_example1.send(completion: .finished)
subject_example2.send(completion: .finished)
print("\nzip on Sequence")
for tuple in zip([1, 2, 3, 4, 5], ["A", "B", "C", "D"]) {
print(tuple)
}
let subject1 = PassthroughSubject<Int, Never>()
let subject2 = PassthroughSubject<String, Never>()
check("Zip") {
subject1.zip(subject2)
}
subject1.send(1)
subject2.send("A")
subject1.send(2)
subject2.send("B")
subject2.send("C")
subject2.send("D")
subject1.send(3)
subject1.send(4)
subject1.send(5)
let subject3 = PassthroughSubject<Int, Never>()
let subject4 = PassthroughSubject<String, Never>()
check("Combine Latest") {
subject3.combineLatest(subject4)
}
subject3.send(1)
subject4.send("A")
subject3.send(2)
subject4.send("B")
subject4.send("C")
subject4.send("D")
subject3.send(3)
subject3.send(4)
subject3.send(5)
| 20.966102 | 57 | 0.742926 |
de4dc101c4ad2c4c157025913592f3305ace31b8 | 1,322 | //
// Car.swift
// Challenge
//
// Created by Matheus Cardoso kuhn on 06/04/19.
// Copyright © 2019 MDT. All rights reserved.
//
import Foundation
class Car: NSObject, Codable {
var id: Int?
@objc public var coordinate: Coordinate?
var fleetType: CarType?
@objc public var heading: NSDecimalNumber?
@objc override public init() {
super.init()
}
enum CodingKeys: String, CodingKey {
case id
case coordinate
case fleetType
case heading
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(Int?.self, forKey: .id)
coordinate = try values.decode(Coordinate?.self, forKey: .coordinate)
fleetType = try values.decode(CarType?.self, forKey: .fleetType)
heading = NSDecimalNumber(floatLiteral: try values.decode(Double.self, forKey: .heading))
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(coordinate, forKey: .coordinate)
try container.encode(fleetType, forKey: .fleetType)
try container.encode(heading?.doubleValue, forKey: .heading)
}
}
| 30.045455 | 97 | 0.651286 |
391e2114526c26bbbc541a0919be4d9891aa061b | 2,691 | //
// Copyright (c) Vatsal Manot
//
import Dispatch
import Swift
import SwiftUI
#if os(iOS) || os(macOS) || os(tvOS) || targetEnvironment(macCatalyst)
public struct AttributedText: AppKitOrUIKitViewRepresentable {
public class AppKitOrUIKitViewType: AppKitOrUIKitView {
private var label = AppKitOrUIKitLabel()
public init() {
super.init(frame: .zero)
self.addSubview(label)
#if os(macOS)
label.autoresizingMask = [.width, .height]
#else
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
#endif
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
#if !os(macOS)
override public func layoutSubviews() {
super.layoutSubviews()
label.preferredMaxLayoutWidth = frame.width
}
#endif
func configure(with attributedText: AttributedText) { label.configure(with: attributedText)
}
}
public let content: NSAttributedString
@Environment(\.accessibilityEnabled) var accessibilityEnabled
@Environment(\.allowsTightening) var allowsTightening
@Environment(\.isEnabled) var isEnabled
@Environment(\.lineLimit) var lineLimit
@Environment(\.minimumScaleFactor) var minimumScaleFactor
#if os(macOS)
@Environment(\.layoutDirection) var layoutDirection
#endif
public init(_ content: NSAttributedString) {
self.content = content
}
public init<S: StringProtocol>(_ content: S) {
self.init(NSAttributedString(string: String(content)))
}
public func makeAppKitOrUIKitView(context: Context) -> AppKitOrUIKitViewType {
AppKitOrUIKitViewType()
}
public func updateAppKitOrUIKitView(_ view: AppKitOrUIKitViewType, context: Context) {
view.configure(with: self)
}
}
// MARK: - Helpers -
extension AppKitOrUIKitLabel {
func configure(with attributedText: AttributedText) {
self.attributedText = attributedText.content
self.minimumScaleFactor = attributedText.minimumScaleFactor
self.numberOfLines = attributedText.lineLimit ?? 0
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
self.allowsDefaultTighteningForTruncation = attributedText.allowsTightening
#endif
#if os(macOS)
self.setAccessibilityEnabled(attributedText.accessibilityEnabled)
self.userInterfaceLayoutDirection = .init(attributedText.layoutDirection)
#endif
}
}
#endif
| 29.25 | 114 | 0.638053 |
f75bbb087580048484d950255175294de481a3b5 | 17,044 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2019 Swift Server Working Group and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import AsyncHTTPClient
import NIO
import NIOConcurrencyHelpers
import NIOHTTP1
import XCTest
class HTTPClientInternalTests: XCTestCase {
typealias Request = HTTPClient.Request
typealias Task = HTTPClient.Task
func testHTTPPartsHandler() throws {
let channel = EmbeddedChannel()
let recorder = RecordingHandler<HTTPClientResponsePart, HTTPClientRequestPart>()
let task = Task<Void>(eventLoop: channel.eventLoop)
try channel.pipeline.addHandler(recorder).wait()
try channel.pipeline.addHandler(TaskHandler(task: task, delegate: TestHTTPDelegate(), redirectHandler: nil, ignoreUncleanSSLShutdown: false)).wait()
var request = try Request(url: "http://localhost/get")
request.headers.add(name: "X-Test-Header", value: "X-Test-Value")
request.body = .string("1234")
XCTAssertNoThrow(try channel.writeOutbound(request))
XCTAssertEqual(3, recorder.writes.count)
var head = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get")
head.headers.add(name: "X-Test-Header", value: "X-Test-Value")
head.headers.add(name: "Host", value: "localhost")
head.headers.add(name: "Content-Length", value: "4")
head.headers.add(name: "Connection", value: "close")
XCTAssertEqual(HTTPClientRequestPart.head(head), recorder.writes[0])
let buffer = ByteBuffer.of(string: "1234")
XCTAssertEqual(HTTPClientRequestPart.body(.byteBuffer(buffer)), recorder.writes[1])
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.head(HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: HTTPResponseStatus.ok))))
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.end(nil)))
}
func testBadHTTPRequest() throws {
let channel = EmbeddedChannel()
let recorder = RecordingHandler<HTTPClientResponsePart, HTTPClientRequestPart>()
let task = Task<Void>(eventLoop: channel.eventLoop)
XCTAssertNoThrow(try channel.pipeline.addHandler(recorder).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(TaskHandler(task: task,
delegate: TestHTTPDelegate(),
redirectHandler: nil,
ignoreUncleanSSLShutdown: false)).wait())
var request = try Request(url: "http://localhost/get")
request.headers.add(name: "X-Test-Header", value: "X-Test-Value")
request.headers.add(name: "Transfer-Encoding", value: "identity")
request.body = .string("1234")
XCTAssertThrowsError(try channel.writeOutbound(request)) { error in
XCTAssertEqual(HTTPClientError.identityCodingIncorrectlyPresent, error as? HTTPClientError)
}
}
func testHTTPPartsHandlerMultiBody() throws {
let channel = EmbeddedChannel()
let delegate = TestHTTPDelegate()
let task = Task<Void>(eventLoop: channel.eventLoop)
let handler = TaskHandler(task: task, delegate: delegate, redirectHandler: nil, ignoreUncleanSSLShutdown: false)
try channel.pipeline.addHandler(handler).wait()
handler.state = .sent
var body = channel.allocator.buffer(capacity: 4)
body.writeStaticString("1234")
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.head(HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: HTTPResponseStatus.ok))))
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.body(body)))
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.body(body)))
switch delegate.state {
case .body(_, let body):
XCTAssertEqual(8, body.readableBytes)
default:
XCTFail("Expecting .body")
}
}
func testProxyStreaming() throws {
let httpBin = HTTPBin()
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
defer {
XCTAssertNoThrow(try httpClient.syncShutdown())
XCTAssertNoThrow(try httpBin.shutdown())
}
let body: HTTPClient.Body = .stream(length: 50) { writer in
do {
var request = try Request(url: "http://localhost:\(httpBin.port)/events/10/1")
request.headers.add(name: "Accept", value: "text/event-stream")
let delegate = HTTPClientCopyingDelegate { part in
writer.write(.byteBuffer(part))
}
return httpClient.execute(request: request, delegate: delegate).futureResult
} catch {
return httpClient.eventLoopGroup.next().makeFailedFuture(error)
}
}
let upload = try! httpClient.post(url: "http://localhost:\(httpBin.port)/post", body: body).wait()
let bytes = upload.body.flatMap { $0.getData(at: 0, length: $0.readableBytes) }
let data = try! JSONDecoder().decode(RequestInfo.self, from: bytes!)
XCTAssertEqual(.ok, upload.status)
XCTAssertEqual("id: 0id: 1id: 2id: 3id: 4id: 5id: 6id: 7id: 8id: 9", data.data)
}
func testProxyStreamingFailure() throws {
let httpBin = HTTPBin()
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
defer {
XCTAssertNoThrow(try httpClient.syncShutdown())
XCTAssertNoThrow(try httpBin.shutdown())
}
var body: HTTPClient.Body = .stream(length: 50) { _ in
httpClient.eventLoopGroup.next().makeFailedFuture(HTTPClientError.invalidProxyResponse)
}
XCTAssertThrowsError(try httpClient.post(url: "http://localhost:\(httpBin.port)/post", body: body).wait())
body = .stream(length: 50) { _ in
do {
var request = try Request(url: "http://localhost:\(httpBin.port)/events/10/1")
request.headers.add(name: "Accept", value: "text/event-stream")
let delegate = HTTPClientCopyingDelegate { _ in
httpClient.eventLoopGroup.next().makeFailedFuture(HTTPClientError.invalidProxyResponse)
}
return httpClient.execute(request: request, delegate: delegate).futureResult
} catch {
return httpClient.eventLoopGroup.next().makeFailedFuture(error)
}
}
XCTAssertThrowsError(try httpClient.post(url: "http://localhost:\(httpBin.port)/post", body: body).wait())
}
func testUploadStreamingBackpressure() throws {
class BackpressureTestDelegate: HTTPClientResponseDelegate {
typealias Response = Void
var _reads = 0
let lock: Lock
let promise: EventLoopPromise<Void>
init(promise: EventLoopPromise<Void>) {
self.lock = Lock()
self.promise = promise
}
var reads: Int {
return self.lock.withLock {
self._reads
}
}
func didReceiveBodyPart(task: HTTPClient.Task<Response>, _ buffer: ByteBuffer) -> EventLoopFuture<Void> {
self.lock.withLockVoid {
self._reads += 1
}
return self.promise.futureResult
}
func didFinishRequest(task: HTTPClient.Task<Response>) throws {}
}
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
let promise: EventLoopPromise<Channel> = httpClient.eventLoopGroup.next().makePromise()
let httpBin = HTTPBin(channelPromise: promise)
defer {
XCTAssertNoThrow(try httpClient.syncShutdown())
XCTAssertNoThrow(try httpBin.shutdown())
}
let request = try Request(url: "http://localhost:\(httpBin.port)/custom")
let delegate = BackpressureTestDelegate(promise: httpClient.eventLoopGroup.next().makePromise())
let future = httpClient.execute(request: request, delegate: delegate).futureResult
let channel = try promise.futureResult.wait()
// Send 3 parts, but only one should be received until the future is complete
let buffer = ByteBuffer.of(string: "1234")
try channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(buffer))).wait()
try channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(buffer))).wait()
try channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(buffer))).wait()
XCTAssertEqual(delegate.reads, 1)
delegate.promise.succeed(())
try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait()
try future.wait()
XCTAssertEqual(delegate.reads, 3)
}
func testRequestURITrailingSlash() throws {
let request1 = try Request(url: "https://someserver.com:8888/some/path?foo=bar#ref")
XCTAssertEqual(request1.url.uri, "/some/path?foo=bar")
let request2 = try Request(url: "https://someserver.com:8888/some/path/?foo=bar#ref")
XCTAssertEqual(request2.url.uri, "/some/path/?foo=bar")
let request3 = try Request(url: "https://someserver.com:8888?foo=bar#ref")
XCTAssertEqual(request3.url.uri, "/?foo=bar")
let request4 = try Request(url: "https://someserver.com:8888/?foo=bar#ref")
XCTAssertEqual(request4.url.uri, "/?foo=bar")
let request5 = try Request(url: "https://someserver.com:8888/some/path")
XCTAssertEqual(request5.url.uri, "/some/path")
let request6 = try Request(url: "https://someserver.com:8888/some/path/")
XCTAssertEqual(request6.url.uri, "/some/path/")
let request7 = try Request(url: "https://someserver.com:8888")
XCTAssertEqual(request7.url.uri, "/")
let request8 = try Request(url: "https://someserver.com:8888/")
XCTAssertEqual(request8.url.uri, "/")
let request9 = try Request(url: "https://someserver.com:8888#ref")
XCTAssertEqual(request9.url.uri, "/")
let request10 = try Request(url: "https://someserver.com:8888/#ref")
XCTAssertEqual(request10.url.uri, "/")
let request11 = try Request(url: "https://someserver.com/some%20path")
XCTAssertEqual(request11.url.uri, "/some%20path")
}
func testChannelAndDelegateOnDifferentEventLoops() throws {
class Delegate: HTTPClientResponseDelegate {
typealias Response = ([Message], [Message])
enum Message {
case head(HTTPResponseHead)
case bodyPart(ByteBuffer)
case sentRequestHead(HTTPRequestHead)
case sentRequestPart(IOData)
case sentRequest
case error(Error)
}
var receivedMessages: [Message] = []
var sentMessages: [Message] = []
private let eventLoop: EventLoop
private let randoEL: EventLoop
init(expectedEventLoop: EventLoop, randomOtherEventLoop: EventLoop) {
self.eventLoop = expectedEventLoop
self.randoEL = randomOtherEventLoop
}
func didSendRequestHead(task: HTTPClient.Task<Response>, _ head: HTTPRequestHead) {
self.eventLoop.assertInEventLoop()
self.sentMessages.append(.sentRequestHead(head))
}
func didSendRequestPart(task: HTTPClient.Task<Response>, _ part: IOData) {
self.eventLoop.assertInEventLoop()
self.sentMessages.append(.sentRequestPart(part))
}
func didSendRequest(task: HTTPClient.Task<Response>) {
self.eventLoop.assertInEventLoop()
self.sentMessages.append(.sentRequest)
}
func didReceiveError(task: HTTPClient.Task<Response>, _ error: Error) {
self.eventLoop.assertInEventLoop()
self.receivedMessages.append(.error(error))
}
public func didReceiveHead(task: HTTPClient.Task<Response>,
_ head: HTTPResponseHead) -> EventLoopFuture<Void> {
self.eventLoop.assertInEventLoop()
self.receivedMessages.append(.head(head))
return self.randoEL.makeSucceededFuture(())
}
func didReceiveBodyPart(task: HTTPClient.Task<Response>,
_ buffer: ByteBuffer) -> EventLoopFuture<Void> {
self.eventLoop.assertInEventLoop()
self.receivedMessages.append(.bodyPart(buffer))
return self.randoEL.makeSucceededFuture(())
}
func didFinishRequest(task: HTTPClient.Task<Response>) throws -> Response {
self.eventLoop.assertInEventLoop()
return (self.receivedMessages, self.sentMessages)
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 3)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let channelEL = group.next()
let delegateEL = group.next()
let randoEL = group.next()
let httpClient = HTTPClient(eventLoopGroupProvider: .shared(group))
let promise: EventLoopPromise<Channel> = httpClient.eventLoopGroup.next().makePromise()
let httpBin = HTTPBin(channelPromise: promise)
defer {
XCTAssertNoThrow(try httpClient.syncShutdown())
XCTAssertNoThrow(try httpBin.shutdown())
}
let body: HTTPClient.Body = .stream(length: 8) { writer in
let buffer = ByteBuffer.of(string: "1234")
return writer.write(.byteBuffer(buffer)).flatMap {
let buffer = ByteBuffer.of(string: "4321")
return writer.write(.byteBuffer(buffer))
}
}
let request = try Request(url: "http://127.0.0.1:\(httpBin.port)/custom",
body: body)
let delegate = Delegate(expectedEventLoop: delegateEL, randomOtherEventLoop: randoEL)
let future = httpClient.execute(request: request,
delegate: delegate,
eventLoop: .init(.testOnly_exact(channelOn: channelEL,
delegateOn: delegateEL))).futureResult
let channel = try promise.futureResult.wait()
// Send 3 parts, but only one should be received until the future is complete
let buffer = ByteBuffer.of(string: "1234")
try channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(buffer))).wait()
try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait()
let (receivedMessages, sentMessages) = try future.wait()
XCTAssertEqual(2, receivedMessages.count)
XCTAssertEqual(4, sentMessages.count)
switch sentMessages.dropFirst(0).first {
case .some(.sentRequestHead(let head)):
XCTAssertEqual(request.url.uri, head.uri)
default:
XCTFail("wrong message")
}
switch sentMessages.dropFirst(1).first {
case .some(.sentRequestPart(.byteBuffer(let buffer))):
XCTAssertEqual("1234", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
default:
XCTFail("wrong message")
}
switch sentMessages.dropFirst(2).first {
case .some(.sentRequestPart(.byteBuffer(let buffer))):
XCTAssertEqual("4321", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
default:
XCTFail("wrong message")
}
switch sentMessages.dropFirst(3).first {
case .some(.sentRequest):
() // OK
default:
XCTFail("wrong message")
}
switch receivedMessages.dropFirst(0).first {
case .some(.head(let head)):
XCTAssertEqual(["transfer-encoding": "chunked"], head.headers)
default:
XCTFail("wrong message")
}
switch receivedMessages.dropFirst(1).first {
case .some(.bodyPart(let buffer)):
XCTAssertEqual("1234", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
default:
XCTFail("wrong message")
}
}
}
| 42.292804 | 170 | 0.615231 |
e877f98c12e8cc17e08f872093ff429fcb3d1fe6 | 2,138 | //
// AppDelegate.swift
// DataTransfer
//
// Created by hengyu on 15/4/7.
// Copyright (c) 2015年 hengyu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.489362 | 285 | 0.753508 |
385304a27d1f1336e0e79a4161b06c1820de0baf | 2,416 | //
// GECalendarPreview.swift
// GECalendarDemo (macOS)
//
// Created by GoEun Jeong on 2021/08/25.
//
import SwiftUI
struct Preview {
static var mutipleEvents: [Event] = [Event(date: Calendar.current.date(byAdding: .weekday, value: -1, to: Date())!, title: "일정 1", color: Color.gray), Event(date: Calendar.current.date(byAdding: .weekday, value: -1, to: Date())!, title: "일정 2 ㅁㅁㅁㅁ", color: Color.gray), Event(date: Date(), title: "asdfasdf", color: Color.green), Event(date: Calendar.current.date(byAdding: .weekday, value: 1, to: Date())!, title: "asdfasdf", color: Color.gray)]
static var events: [Date] = [Date(), Calendar.current.date(byAdding: .weekday, value: -1, to: Date())!, Calendar.current.date(byAdding: .weekday, value: +1, to: Date())!]
static var headerDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY MMMM"
return formatter
}()
}
struct GECalendarPreviews: PreviewProvider {
static let appearance = Appearance(selectionShape: .roundedRectangle(cornerRadius: 10), multipleEvents: Preview.mutipleEvents, isMultipleEvents: true, headerType: .leading)
static let appearance1 = Appearance(events: Preview.events, eventType: .circle, headerType: .center, locale: Locale(identifier: "en-US"), headerDateFormatter: Preview.headerDateFormatter)
static let appearance2 = Appearance(todayColor: Color.clear, defaultColor: Color.blue.opacity(0.2))
static let appearance3 = Appearance(events: Preview.events, eventType: .text, eventColor: Color.red, headerType: .trailing)
static let appearance4 = Appearance(eventType: .circle, selectionShape: .circle, multipleEvents: Preview.mutipleEvents, isMultipleEvents: true)
@State static var date: Date? = Date()
@State static var nilDate: Date? = nil
static var previews: some View {
Group {
// Multiple Events - square
GECalendar(selectedDate: $date, appearance: appearance)
// Multiple Events - circle
GECalendar(selectedDate: $date, appearance: appearance4)
// English
GECalendar(selectedDate: $date, appearance: appearance1)
// today Color change
GECalendar(selectedDate: $nilDate, appearance: appearance2)
// Events - text
GECalendar(selectedDate: $nilDate, appearance: appearance3)
}
}
}
| 53.688889 | 450 | 0.685017 |
11492fee29c24ac218380177fdd5d331d85bc0e6 | 829 | //
// ImageGridView.swift
// Music
//
// Created by Mathias Quintero on 12/23/19.
// Copyright © 2019 Mathias Quintero. All rights reserved.
//
import Foundation
import SwiftUI
struct ImageGridView: View {
let images: [URL]
var body: some View {
guard let first = images.first else { return AnyView(Text("")) }
if images.count < 4 {
return AnyView(Image.artwork(first))
} else {
let grid = VStack(spacing: 0) {
HStack(spacing: 0) {
Image.artwork(images[0])
Image.artwork(images[1])
}
HStack(spacing: 0) {
Image.artwork(images[2])
Image.artwork(images[3])
}
}
return AnyView(grid)
}
}
}
| 24.382353 | 72 | 0.499397 |
fffc681e605abd98484d7a563857b142dfa2be4d | 6,817 | // Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class GPKGLayersViewController: UITableViewController {
var map: AGSMap?
var allLayers: [AGSLayer] = [] {
didSet {
var rasterCount = 1
for layer in allLayers where layer is AGSRasterLayer &&
layer.name.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty {
// Give raster layers a name
layer.name = "Raster Layer \(rasterCount)"
rasterCount += 1
}
}
}
private var layersInMap: [AGSLayer] {
// 0 is the bottom-most layer on the map, but first cell in a table.
// By reversing the layer order from the map, we match the UITableView order.
return map?.operationalLayers.reversed() as? [AGSLayer] ?? []
}
private var layersNotInMap: [AGSLayer] {
guard map != nil else {
return allLayers
}
return allLayers.filter({ layer -> Bool in
return !layersInMap.contains(layer)
})
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.isEditing = true
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? layersInMap.count : layersNotInMap.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "Layers on the map" : "Layers not on the map"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let layerCell = tableView.dequeueReusableCell(withIdentifier: "GPKGLayersCell", for: indexPath) as! GPKGLayerTableCell
if indexPath.section == 0 {
// Set up the cell for a layer that is on the map.
layerCell.agsLayer = layersInMap[indexPath.row]
} else {
// Set up the cell for a layer that is NOT on the map.
layerCell.agsLayer = layersNotInMap[indexPath.row]
}
return layerCell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 0
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// A row for a layer that's on the map was dragged in the table view.
// Update the map's layers to reflect the change in order.
// Get the layer that was dragged.
if let layer = layer(forTableView: tableView, andIndexPath: sourceIndexPath),
let layers = map?.operationalLayers {
// Remove the layer from the map.
layers.remove(layer)
// Re-insert it at the position it was dragged to.
layers.insert(layer, at: layers.count - destinationIndexPath.row)
}
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
if indexPath.section == 0 {
return "Remove from map"
}
return nil
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
switch indexPath.section {
case 0:
return .delete
case 1:
return .insert
default:
return .none
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Ensure we are able to get the AGSLayer from the row.
guard let layer = layer(forTableView: tableView, andIndexPath: indexPath) else {
print("Could not get layer for index path")
return
}
switch editingStyle {
case .delete:
tableView.beginUpdates()
// Remove the layer from the map.
map?.operationalLayers.remove(layer)
// Remove the row from the section of layers in the map.
tableView.deleteRows(at: [indexPath], with: .automatic)
// Insert the removed row back in the section for layers not in the map.
if let index = layersNotInMap.index(of: layer) {
let newIndexPath = IndexPath(row: index, section: 1)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
tableView.endUpdates()
case .insert:
tableView.beginUpdates()
// Add it on top of any other layers.
map?.operationalLayers.add(layer)
// Remove the row representing the layer before it was added to the map.
tableView.deleteRows(at: [indexPath], with: .fade)
// Add a row representing the layer now it's at the top of the map's layers.
let newIndexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [newIndexPath], with: .fade)
tableView.endUpdates()
default:
return
}
}
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if sourceIndexPath.section != proposedDestinationIndexPath.section {
return sourceIndexPath
} else {
return proposedDestinationIndexPath
}
}
private func layer(forTableView tableView: UITableView, andIndexPath indexPath: IndexPath) -> AGSLayer? {
return (tableView.cellForRow(at: indexPath) as? GPKGLayerTableCell)?.agsLayer
}
}
| 38.297753 | 189 | 0.619041 |
1c4ca1c0090c44d2be64af66d0c99be77c408d27 | 4,680 | //
// WBSelectGenderView.swift
// ACN_Wallet
//
// Created by Zhouheng on 2020/5/12.
// Copyright © 2020 TTC. All rights reserved.
//
import UIKit
class WBSelectGenderView: WBAlertBaseView {
/// 确定
var confirmClick:((Int) -> ())?
var selectedGender: Int = 3
static var isShowed = false
init() {
super.init(frame: UIScreen.main.bounds)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
titleLabel.text = "请选择性别"
customView.snp.updateConstraints { (make) in
make.height.equalTo(96)
}
customView.addSubview(maleButton)
customView.addSubview(maleLabel)
maleButton.snp.makeConstraints { (make) in
make.left.top.equalTo(0)
make.height.equalTo(48)
make.width.equalTo(71)
}
maleLabel.snp.makeConstraints { (make) in
make.left.equalTo(maleButton.snp.right)
make.centerY.equalTo(maleButton)
make.right.equalTo(-24)
}
customView.addSubview(femaleButton)
customView.addSubview(femaleLabel)
femaleButton.snp.makeConstraints { (make) in
make.left.bottom.equalTo(0)
make.height.equalTo(48)
make.width.equalTo(71)
}
femaleLabel.snp.makeConstraints { (make) in
make.left.equalTo(femaleButton.snp.right)
make.centerY.equalTo(femaleButton)
make.right.equalTo(-24)
}
}
/// MARK: --- action
@objc func maleButtonClick(_ sender: UIButton) {
femaleButton.isSelected = false
sender.isSelected = true
selectedGender = 2
}
@objc func femaleButtonClick(_ sender: UIButton) {
maleButton.isSelected = false
sender.isSelected = true
selectedGender = 1
}
@objc func maleTapClick(_ gesture: UITapGestureRecognizer) {
femaleButton.isSelected = false
maleButton.isSelected = true
selectedGender = 2
}
@objc func femaleTapClick(_ gesture: UITapGestureRecognizer) {
maleButton.isSelected = false
femaleButton.isSelected = true
selectedGender = 1
}
@objc override func buttonClick(_ sender: UIButton) {
super.buttonClick(sender)
dismiss(completion: {
WBSelectGenderView.isShowed = false
self.confirmClick?(self.selectedGender)
})
}
@discardableResult
override func show(_ superview: UIView? = nil) -> Bool {
if WBSelectGenderView.isShowed {
return false
} else {
let showed = super.show(superview)
if showed {
WBSelectGenderView.isShowed = true
}
return showed
}
}
override func cancel() {
WBSelectGenderView.isShowed = false
super.cancel()
}
/// MARK: --- lazy var
lazy var maleButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "wb_unselect"), for: .normal)
button.setImage(UIImage(named: "wb_select"), for: .selected)
button.addTarget(self, action: #selector(maleButtonClick(_:)), for: .touchUpInside)
return button
}()
lazy var maleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.black
label.text = "男"
label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(maleTapClick(_:)))
label.addGestureRecognizer(tap)
return label
}()
lazy var femaleButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "wb_unselect"), for: .normal)
button.setImage(UIImage(named: "wb_select"), for: .selected)
button.addTarget(self, action: #selector(femaleButtonClick(_:)), for: .touchUpInside)
return button
}()
lazy var femaleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize:16)
label.textColor = UIColor.black
label.text = "女"
label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(femaleTapClick(_:)))
label.addGestureRecognizer(tap)
return label
}()
}
| 28.888889 | 93 | 0.584402 |
eb576ca1f859e91cdf6393004b512a08c54f83e7 | 6,196 | public func format<A>(_ formatter: Formatter<String, (A) -> String>, _ a: A) -> String {
return format(formatter)(a)
}
public func format<A, B>(_ formatter: Formatter<String, (A) -> (B) -> String>, _ a: A, _ b: B) -> String {
return format(formatter)(a)(b)
}
public func format<A, B, C>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> String>, _ a: A, _ b: B, _ c: C) -> String {
return format(formatter)(a)(b)(c)
}
public func format<A, B, C, D>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> String>, _ a: A, _ b: B, _ c: C, _ d: D) -> String {
return format(formatter)(a)(b)(c)(d)
}
public func format<A, B, C, D, E>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> String {
return format(formatter)(a)(b)(c)(d)(e)
}
public func format<A, B, C, D, E, F>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)
}
public func format<A, B, C, D, E, F, G>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)
}
public func format<A, B, C, D, E, F, G, H>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)
}
public func format<A, B, C, D, E, F, G, H, I>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)(i)
}
public func format<A, B, C, D, E, F, G, H, I, J>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)
}
public func format<A, B, C, D, E, F, G, H, I, J, K>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> (K) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)
}
public func format<A, B, C, D, E, F, G, H, I, J, K, L>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> (K) -> (L) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K, _ l: L) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)
}
public func format<A, B, C, D, E, F, G, H, I, J, K, L, M>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> (K) -> (L) -> (M) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K, _ l: L, _ m: M) -> String {
return format(formatter)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)
}
public func print<A>(_ formatter: Formatter<String, (A) -> String>, _ a: A) {
print(format(formatter, a))
}
public func print<A, B>(_ formatter: Formatter<String, (A) -> (B) -> String>, _ a: A, _ b: B) {
print(format(formatter, a, b))
}
public func print<A, B, C>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> String>, _ a: A, _ b: B, _ c: C) {
print(format(formatter, a, b, c))
}
public func print<A, B, C, D>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> String>, _ a: A, _ b: B, _ c: C, _ d: D) {
print(format(formatter, a, b, c, d))
}
public func print<A, B, C, D, E>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E) {
print(format(formatter, a, b, c, d, e))
}
public func print<A, B, C, D, E, F>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) {
print(format(formatter, a, b, c, d, e, f))
}
public func print<A, B, C, D, E, F, G>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) {
print(format(formatter, a, b, c, d, e, f, g))
}
public func print<A, B, C, D, E, F, G, H>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) {
print(format(formatter, a, b, c, d, e, f, g, h))
}
public func print<A, B, C, D, E, F, G, H, I>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) {
print(format(formatter, a, b, c, d, e, f, g, h, i))
}
public func print<A, B, C, D, E, F, G, H, I, J>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) {
print(format(formatter, a, b, c, d, e, f, g, h, i, j))
}
public func print<A, B, C, D, E, F, G, H, I, J, L>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> (L) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ l: L) {
print(format(formatter, a, b, c, d, e, f, g, h, i, j, l))
}
public func print<A, B, C, D, E, F, G, H, I, J, L, M>(_ formatter: Formatter<String, (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> (G) -> (H) -> (I) -> (J) -> (L) -> (M) -> String>, _ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ l: L, _ m: M) {
print(format(formatter, a, b, c, d, e, f, g, h, i, j, l, m))
}
// MARK:
public func format<A>(_ formatter: () -> Formatter<String, (A) -> String>, _ a: A) -> String {
return format(formatter)(a)
}
public func print<A>(_ formatter: () -> Formatter<String, (A) -> String>, _ a: A) {
print(format(formatter, a))
}
| 56.327273 | 304 | 0.471917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.