repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
pyconjp/pyconjp-ios | WebAPIFramework/Error/APIError.swift | 1 | 227 | //
// APIError.swift
// PyConJP
//
// Created by Yutaro Muta on 2017/06/01.
// Copyright © 2017 PyCon JP. All rights reserved.
//
import Foundation
public enum APIError: Error {
case failureParse
case nullData
}
| mit |
Bouke/LedgerTools | Sources/ledger-import-csv/String+Swift.swift | 1 | 136 | extension String {
func pad(_ length: Int) -> String {
return padding(toLength: length, withPad: " ", startingAt: 0)
}
} | mit |
modnovolyk/MAVLinkSwift | Sources/AirspeedAutocalArdupilotmegaMsg.swift | 1 | 2655 | //
// AirspeedAutocalArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Airspeed auto-calibration
public struct AirspeedAutocal {
/// GPS velocity north m/s
public let vx: Float
/// GPS velocity east m/s
public let vy: Float
/// GPS velocity down m/s
public let vz: Float
/// Differential pressure pascals
public let diffPressure: Float
/// Estimated to true airspeed ratio
public let eas2tas: Float
/// Airspeed ratio
public let ratio: Float
/// EKF state x
public let stateX: Float
/// EKF state y
public let stateY: Float
/// EKF state z
public let stateZ: Float
/// EKF Pax
public let pax: Float
/// EKF Pby
public let pby: Float
/// EKF Pcz
public let pcz: Float
}
extension AirspeedAutocal: Message {
public static let id = UInt8(174)
public static var typeName = "AIRSPEED_AUTOCAL"
public static var typeDescription = "Airspeed auto-calibration"
public static var fieldDefinitions: [FieldDefinition] = [("vx", 0, "Float", 0, "GPS velocity north m/s"), ("vy", 4, "Float", 0, "GPS velocity east m/s"), ("vz", 8, "Float", 0, "GPS velocity down m/s"), ("diffPressure", 12, "Float", 0, "Differential pressure pascals"), ("eas2tas", 16, "Float", 0, "Estimated to true airspeed ratio"), ("ratio", 20, "Float", 0, "Airspeed ratio"), ("stateX", 24, "Float", 0, "EKF state x"), ("stateY", 28, "Float", 0, "EKF state y"), ("stateZ", 32, "Float", 0, "EKF state z"), ("pax", 36, "Float", 0, "EKF Pax"), ("pby", 40, "Float", 0, "EKF Pby"), ("pcz", 44, "Float", 0, "EKF Pcz")]
public init(data: Data) throws {
vx = try data.number(at: 0)
vy = try data.number(at: 4)
vz = try data.number(at: 8)
diffPressure = try data.number(at: 12)
eas2tas = try data.number(at: 16)
ratio = try data.number(at: 20)
stateX = try data.number(at: 24)
stateY = try data.number(at: 28)
stateZ = try data.number(at: 32)
pax = try data.number(at: 36)
pby = try data.number(at: 40)
pcz = try data.number(at: 44)
}
public func pack() throws -> Data {
var payload = Data(count: 48)
try payload.set(vx, at: 0)
try payload.set(vy, at: 4)
try payload.set(vz, at: 8)
try payload.set(diffPressure, at: 12)
try payload.set(eas2tas, at: 16)
try payload.set(ratio, at: 20)
try payload.set(stateX, at: 24)
try payload.set(stateY, at: 28)
try payload.set(stateZ, at: 32)
try payload.set(pax, at: 36)
try payload.set(pby, at: 40)
try payload.set(pcz, at: 44)
return payload
}
}
| mit |
wbaumann/SmartReceiptsiOS | SmartReceipts/Modules/Edit Trip/EditTripRouter.swift | 2 | 534 | //
// EditTripRouter.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 12/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
class EditTripRouter: Router {
func close() {
_view.viewController.navigationController?.dismiss(animated: true, completion: nil)
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension EditTripRouter {
var presenter: EditTripPresenter {
return _presenter as! EditTripPresenter
}
}
| agpl-3.0 |
apple/swift | test/ModuleInterface/clang-args-transitive-availability.swift | 1 | 2216 | // This test ensures that the parent invocation's '-Xcc X' flags are inherited when building dependency modules
// RUN: %empty-directory(%t)
// Just running a compile is useful to make sure it succeeds because that means the transitive Clang module dependency
// received the TANGERINE macro
// RUN: %target-swift-frontend -typecheck -strict-implicit-module-context %s -I %S/Inputs/macro-only-module -Xcc -DTANGERINE=1 -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import
// RUN: %target-swift-frontend -scan-dependencies -strict-implicit-module-context %s -o %t/deps.json -I %S/Inputs/macro-only-module -Xcc -DTANGERINE=1 -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import
// RUN: %FileCheck %s < %t/deps.json
import ImportsMacroSpecificClangModule
// CHECK: "directDependencies": [
// CHECK-NEXT: {
// CHECK-DAG: "swift": "ImportsMacroSpecificClangModule"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-DAG: "swift": "Swift"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-DAG: "swift": "SwiftOnoneSupport"
// CHECK-NEXT: }
// CHECK-NEXT: ],
//CHECK: "swift": "ImportsMacroSpecificClangModule"
//CHECK-NEXT: },
//CHECK-NEXT: {
//CHECK-NEXT: "modulePath": "{{.*}}{{/|\\}}ImportsMacroSpecificClangModule-{{.*}}.swiftmodule",
//CHECK-NEXT: "sourceFiles": [
//CHECK-NEXT: ],
//CHECK-NEXT: "directDependencies": [
//CHECK-NEXT: {
//CHECK-NEXT: "clang": "OnlyWithMacro"
// CHECK: "clang": "OnlyWithMacro"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "modulePath": "{{.*}}{{/|\\}}OnlyWithMacro-{{.*}}.pcm",
// CHECK-NEXT: "sourceFiles": [
// CHECK-DAG: "{{.*}}OnlyWithMacro.h"
// CHECK-DAG: "{{.*}}module.modulemap"
// CHECK-NEXT: ],
// CHECK-NEXT: "directDependencies": [
// CHECK-NEXT: ],
// CHECK-NEXT: "details": {
// CHECK-NEXT: "clang": {
// CHECK-NEXT: "moduleMapPath": "{{.*}}module.modulemap",
// CHECK-NEXT: "contextHash": "{{.*}}",
// CHECK-NEXT: "commandLine": [
// CHECK: "TANGERINE=1",
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/25686-swift-parser-parseexprclosure.swift | 1 | 452 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
import a}class A{struct Q<T where A:C{class d}let g={
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/06684-swift-nominaltypedecl-preparelookuptable.swift | 11 | 374 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
protocol B : A {
}
class d<I : T where g: where T {
class A {
class d<c : S<T, f: A {
}
class c : d {
class A<Int>
typealias e : A {
func a(")
let a {
protocol b {
class d>() {
}
typealias e : e
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/03114-swift-sourcemanager-getmessage.swift | 11 | 280 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
let a {
}
protocol c : B<T {
class b<1 {
struct A {
class func b: b {
enum b {
class
case c,
let g =
| mit |
cnoon/swift-compiler-crashes | fixed/23244-swift-parser-parsedeclfunc.swift | 11 | 233 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d{enum A{func f<T{var C{class C{func g{class A:A{class A
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/13084-llvm-raw-fd-ostream-write-impl.swift | 11 | 204 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func<{class a<T where g:U class b:a | mit |
lucaslimapoa/NewsAPISwift | Source/Provider/URLRequestBuilder.swift | 1 | 709 | //
// URLRequestBuilder.swift
// NewsAPISwift
//
// Created by Lucas Lima on 22/06/18.
// Copyright © 2018 Lucas Lima. All rights reserved.
//
import Foundation
class URLRequestBuilder {
var url: URL?
var headers: [String: String]?
init(url: URL? = nil, headers: [String: String]? = nil) {
self.url = url
self.headers = headers
}
}
extension URLRequest {
typealias BuilderClosure = ((URLRequestBuilder) -> ())
init?(builder: URLRequestBuilder) {
guard let url = builder.url else { return nil }
self.init(url: url)
if let headers = builder.headers {
self.allHTTPHeaderFields = headers
}
}
}
| mit |
kostiakoval/Natalie | NatalieExample/NatalieExample/Storyboards.swift | 1 | 10018 | //
// Autogenerated by Natalie - Storyboard Generator Script.
// http://blog.krzyzanowskim.com
//
import UIKit
//MARK: - Storyboards
extension UIStoryboard {
func instantiateViewController<T: UIViewController where T: IdentifiableProtocol>(type: T.Type) -> T? {
let instance = type.init()
if let identifier = instance.identifier {
return self.instantiateViewControllerWithIdentifier(identifier) as? T
}
return nil
}
}
protocol Storyboard {
static var storyboard: UIStoryboard { get }
static var identifier: String { get }
}
struct Storyboards {
struct Main: Storyboard {
static let identifier = "Main"
static var storyboard: UIStoryboard {
return UIStoryboard(name: self.identifier, bundle: nil)
}
static func instantiateInitialViewController() -> UINavigationController {
return self.storyboard.instantiateInitialViewController() as! UINavigationController
}
static func instantiateViewControllerWithIdentifier(identifier: String) -> UIViewController {
return self.storyboard.instantiateViewControllerWithIdentifier(identifier)
}
static func instantiateViewController<T: UIViewController where T: IdentifiableProtocol>(type: T.Type) -> T? {
return self.storyboard.instantiateViewController(type)
}
static func instantiateMainViewController() -> MainViewController {
return self.storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController
}
static func instantiateSecondViewController() -> ScreenTwoViewController {
return self.storyboard.instantiateViewControllerWithIdentifier("secondViewController") as! ScreenTwoViewController
}
static func instantiateScreenOneViewController() -> ScreenOneViewController {
return self.storyboard.instantiateViewControllerWithIdentifier("Screen One ViewController") as! ScreenOneViewController
}
}
}
//MARK: - ReusableKind
enum ReusableKind: String, CustomStringConvertible {
case TableViewCell = "tableViewCell"
case CollectionViewCell = "collectionViewCell"
var description: String { return self.rawValue }
}
//MARK: - SegueKind
enum SegueKind: String, CustomStringConvertible {
case Relationship = "relationship"
case Show = "show"
case Presentation = "presentation"
case Embed = "embed"
case Unwind = "unwind"
case Push = "push"
case Modal = "modal"
case Popover = "popover"
case Replace = "replace"
case Custom = "custom"
var description: String { return self.rawValue }
}
//MARK: - SegueProtocol
public protocol IdentifiableProtocol: Equatable {
var identifier: String? { get }
}
public protocol SegueProtocol: IdentifiableProtocol {
}
public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {
return lhs.identifier == rhs.identifier
}
public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {
return lhs.identifier == rhs.identifier
}
public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {
return lhs.identifier == rhs
}
public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {
return lhs.identifier == rhs
}
public func ==<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {
return lhs == rhs.identifier
}
public func ~=<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {
return lhs == rhs.identifier
}
//MARK: - ReusableViewProtocol
public protocol ReusableViewProtocol: IdentifiableProtocol {
var viewType: UIView.Type? { get }
}
public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {
return lhs.identifier == rhs.identifier
}
//MARK: - Protocol Implementation
extension UIStoryboardSegue: SegueProtocol {
}
extension UICollectionReusableView: ReusableViewProtocol {
public var viewType: UIView.Type? { return self.dynamicType }
public var identifier: String? { return self.reuseIdentifier }
}
extension UITableViewCell: ReusableViewProtocol {
public var viewType: UIView.Type? { return self.dynamicType }
public var identifier: String? { return self.reuseIdentifier }
}
//MARK: - UIViewController extension
extension UIViewController {
func performSegue<T: SegueProtocol>(segue: T, sender: AnyObject?) {
if let identifier = segue.identifier {
performSegueWithIdentifier(identifier, sender: sender)
}
}
func performSegue<T: SegueProtocol>(segue: T) {
performSegue(segue, sender: nil)
}
}
//MARK: - UICollectionView
extension UICollectionView {
func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UICollectionViewCell? {
if let identifier = reusable.identifier {
return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: forIndexPath)
}
return nil
}
func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {
if let type = reusable.viewType, identifier = reusable.identifier {
registerClass(type, forCellWithReuseIdentifier: identifier)
}
}
func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, forIndexPath: NSIndexPath!) -> UICollectionReusableView? {
if let identifier = reusable.identifier {
return dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier, forIndexPath: forIndexPath)
}
return nil
}
func registerReusable<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {
if let type = reusable.viewType, identifier = reusable.identifier {
registerClass(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)
}
}
}
//MARK: - UITableView
extension UITableView {
func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UITableViewCell? {
if let identifier = reusable.identifier {
return dequeueReusableCellWithIdentifier(identifier, forIndexPath: forIndexPath)
}
return nil
}
func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {
if let type = reusable.viewType, identifier = reusable.identifier {
registerClass(type, forCellReuseIdentifier: identifier)
}
}
func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) -> UITableViewHeaderFooterView? {
if let identifier = reusable.identifier {
return dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
return nil
}
func registerReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) {
if let type = reusable.viewType, identifier = reusable.identifier {
registerClass(type, forHeaderFooterViewReuseIdentifier: identifier)
}
}
}
//MARK: - MainViewController
extension UIStoryboardSegue {
func selection() -> MainViewController.Segue? {
if let identifier = self.identifier {
return MainViewController.Segue(rawValue: identifier)
}
return nil
}
}
extension MainViewController: IdentifiableProtocol {
var identifier: String? { return "MainViewController" }
static var identifier: String? { return "MainViewController" }
}
extension MainViewController {
enum Segue: String, CustomStringConvertible, SegueProtocol {
case ScreenOneSegueButton = "Screen One Segue Button"
case ScreenOneSegue = "ScreenOneSegue"
case ScreenTwoSegue = "ScreenTwoSegue"
case SceneOneGestureRecognizerSegue = "SceneOneGestureRecognizerSegue"
var kind: SegueKind? {
switch (self) {
case ScreenOneSegueButton:
return SegueKind(rawValue: "push")
case ScreenOneSegue:
return SegueKind(rawValue: "push")
case ScreenTwoSegue:
return SegueKind(rawValue: "push")
case SceneOneGestureRecognizerSegue:
return SegueKind(rawValue: "push")
}
}
var destination: UIViewController.Type? {
switch (self) {
case ScreenOneSegueButton:
return ScreenOneViewController.self
case ScreenOneSegue:
return ScreenOneViewController.self
case ScreenTwoSegue:
return ScreenTwoViewController.self
case SceneOneGestureRecognizerSegue:
return ScreenOneViewController.self
}
}
var identifier: String? { return self.description }
var description: String { return self.rawValue }
}
}
//MARK: - ScreenTwoViewController
extension ScreenTwoViewController: IdentifiableProtocol {
var identifier: String? { return "secondViewController" }
static var identifier: String? { return "secondViewController" }
}
extension ScreenTwoViewController {
enum Reusable: String, CustomStringConvertible, ReusableViewProtocol {
case MyCell = "MyCell"
var kind: ReusableKind? {
switch (self) {
case MyCell:
return ReusableKind(rawValue: "tableViewCell")
}
}
var viewType: UIView.Type? {
switch (self) {
default:
return nil
}
}
var identifier: String? { return self.description }
var description: String { return self.rawValue }
}
}
//MARK: - ScreenOneViewController
extension ScreenOneViewController: IdentifiableProtocol {
var identifier: String? { return "Screen One ViewController" }
static var identifier: String? { return "Screen One ViewController" }
}
| mit |
scottrhoyt/Noonian | Sources/NoonianKit/Utilities/Tasks/ConfigurableItem.swift | 1 | 241 | //
// ConfigurableItem.swift
// Noonian
//
// Created by Scott Hoyt on 11/2/16.
// Copyright © 2016 Scott Hoyt. All rights reserved.
//
import Foundation
protocol ConfigurableItem {
init(name: String, configuration: Any) throws
}
| mit |
lorentey/swift | test/decl/protocol/conforms/Inputs/fixit_stub_mutability_proto_module.swift | 25 | 124 | public protocol ExternalMutabilityProto {
mutating func foo()
subscript() -> Int { mutating get nonmutating set }
}
| apache-2.0 |
apple/swift-nio | Tests/NIOPosixTests/NIOThreadPoolTest+XCTest.swift | 1 | 1184 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// NIOThreadPoolTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension NIOThreadPoolTest {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (NIOThreadPoolTest) -> () throws -> Void)] {
return [
("testThreadNamesAreSetUp", testThreadNamesAreSetUp),
("testThreadPoolStartsMultipleTimes", testThreadPoolStartsMultipleTimes),
]
}
}
| apache-2.0 |
Headmast/openfights | MoneyHelper/Screens/Infromation/View/InfromationViewOutput.swift | 1 | 254 | //
// InfromationViewOutput.swift
// MoneyHelper
//
// Created by Kirill Klebanov on 16/09/2017.
// Copyright © 2017 Surf. All rights reserved.
//
protocol InfromationViewOutput {
/// Notify presenter that view is ready
func viewLoaded()
}
| apache-2.0 |
gregomni/swift | test/DebugInfo/inout.swift | 10 | 2583 | // RUN: %target-swift-frontend %s -emit-ir -g -module-name inout -o %t.ll
// RUN: cat %t.ll | %FileCheck %s
// RUN: cat %t.ll | %FileCheck %s --check-prefix=PROMO-CHECK
// RUN: cat %t.ll | %FileCheck %s --check-prefix=FOO-CHECK
// LValues are direct values, too. They are reference types, though.
func Close(_ fn: () -> Int64) { fn() }
typealias MyFloat = Float
// CHECK: define hidden swiftcc void @"$s5inout13modifyFooHeap{{[_0-9a-zA-Z]*}}F"
// CHECK: %[[ALLOCA:.*]] = alloca %Ts5Int64V*
// CHECK: call void @llvm.dbg.declare(metadata
// CHECK-SAME: %[[ALLOCA]], metadata ![[A:[0-9]+]]
// Closure with promoted capture.
// PROMO-CHECK: define {{.*}}@"$s5inout13modifyFooHeapyys5Int64Vz_SftFADyXEfU_"
// PROMO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
// PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata !DIExpression(DW_OP_deref))
// PROMO-CHECK: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
// PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1,{{.*}} type: ![[INT]]
func modifyFooHeap(_ a: inout Int64,
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a", arg: 1{{.*}} line: [[@LINE-1]],{{.*}} type: ![[RINT:[0-9]+]]
// CHECK-DAG: ![[RINT]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
_ b: MyFloat)
{
let b = b
if (b > 2.71) {
a = a + 12// Set breakpoint here
}
// Close over the variable to disable promotion of the inout shadow.
Close({ a })
}
// Inout reference type.
// FOO-CHECK: define {{.*}}@"$s5inout9modifyFooyys5Int64Vz_SftF"
// FOO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
// FOO-CHECK-SAME: metadata ![[U:[0-9]+]], metadata !DIExpression(DW_OP_deref))
func modifyFoo(_ u: inout Int64,
// FOO-CHECK-DAG: !DILocalVariable(name: "v", arg: 2{{.*}} line: [[@LINE+3]],{{.*}} type: ![[LET_MYFLOAT:[0-9]+]]
// FOO-CHECK-DAG: [[U]] = !DILocalVariable(name: "u", arg: 1,{{.*}} line: [[@LINE-2]],{{.*}} type: ![[RINT:[0-9]+]]
// FOO-CHECK-DAG: ![[RINT]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
_ v: MyFloat)
// FOO-CHECK-DAG: ![[LET_MYFLOAT]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[MYFLOAT:[0-9]+]])
// FOO-CHECK-DAG: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s5inout7MyFloataD",{{.*}} baseType: ![[FLOAT:[0-9]+]]
// FOO-CHECK-DAG: ![[FLOAT]] = !DICompositeType({{.*}}identifier: "$sSfD"
{
if (v > 2.71) {
u = u - 41
}
}
func main() -> Int64 {
var c = 11 as Int64
modifyFoo(&c, 3.14)
var d = 64 as Int64
modifyFooHeap(&d, 1.41)
return 0
}
main()
| apache-2.0 |
SimonFairbairn/Stormcloud | Tests/StormcloudTests/StormcloudCoreDataTests.swift | 1 | 19247 | //
// StormcloudCoreDataTests.swift
// Stormcloud
//
// Created by Simon Fairbairn on 21/10/2015.
// Copyright © 2015 Simon Fairbairn. All rights reserved.
//
import CoreData
import XCTest
@testable import Stormcloud
enum StormcloudTestError : Error {
case invalidContext
case couldntCreateManagedObject
}
class StormcloudCoreDataTests: StormcloudTestsBaseClass, StormcloudRestoreDelegate {
let totalTags = 4
let totalClouds = 2
let totalRaindrops = 2
var stack : CoreDataStack!
override func setUp() {
self.fileExtension = "json"
stack = CoreDataStack(modelName: "clouds")
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func insertCloudWithNumber(_ number : Int) throws -> Cloud {
if let context = self.stack.managedObjectContext {
do {
let didRain : Bool? = ( number % 2 == 0 ) ? true : nil
return try Cloud.insertCloudWithName("Cloud \(number)", order: number, didRain: didRain, inContext: context)
} catch {
XCTFail("Couldn't create cloud")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func insertTagWithName(_ name : String ) throws -> Tag {
if let context = self.stack.managedObjectContext {
do {
return try Tag.insertTagWithName(name, inContext: context)
} catch {
XCTFail("Couldn't create drop")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func insertDropWithType(_ type : RaindropType, cloud : Cloud ) throws -> Raindrop {
if let context = self.stack.managedObjectContext {
do {
return try Raindrop.insertRaindropWithType(type, withCloud: cloud, inContext: context)
} catch {
XCTFail("Couldn't create drop")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func setupStack() {
let expectation = self.expectation(description: "Stack Setup")
stack.setupStore { () -> Void in
XCTAssertNotNil(self.stack.managedObjectContext)
expectation.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
func addTags() -> [Tag] {
print("Adding tags")
var tags : [Tag] = []
do {
let tag1 = try self.insertTagWithName("Wet")
let tag2 = try self.insertTagWithName("Windy")
let tag3 = try self.insertTagWithName("Dark")
let tag4 = try self.insertTagWithName("Thundery")
tags.append(tag1)
tags.append(tag2)
tags.append(tag3)
tags.append(tag4)
} catch {
XCTFail("Failed to insert tags")
}
return tags
}
func addObjectsWithNumber(_ number : Int, tags : [Tag] = []) {
let cloud : Cloud
do {
cloud = try self.insertCloudWithNumber(number)
let drop1 = try self.insertDropWithType(RaindropType.Heavy, cloud: cloud)
let drop2 = try self.insertDropWithType(RaindropType.Light, cloud: cloud)
cloud.addToRaindrops(drop1)
cloud.addToRaindrops(drop2)
if tags.count > 0 {
cloud.tags = NSSet(array: tags)
}
} catch {
XCTFail("Failed to create data: \(error)")
}
}
func backupCoreData(with manager : Stormcloud) {
guard let context = self.stack.managedObjectContext else {
XCTFail("Context not available")
return
}
let expectation = self.expectation(description: "Insert expectation")
self.stack.save()
manager.backupCoreDataEntities(in: context) { (error, metadata) -> () in
if let _ = error {
XCTFail("Failed to back up Core Data entites")
}
expectation.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
func test_setupCoreData() {
let manager = Stormcloud()
manager.delegate = self
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(5, tags: tags)
}
func testThatBackingUpIndividualObjectsWorks() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(5, tags: tags)
waitForFiles(manager)
guard let context = self.stack.managedObjectContext else {
XCTFail("Context not available")
return
}
self.stack.save()
let expectation = self.expectation(description: "Insert expectation")
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
let objects = try! context.fetch(request)
manager.backupCoreDataObjects( objects: objects) { (error, metadata) -> () in
if let hasError = error {
XCTFail("Failed to back up Core Data entites: \(hasError)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 30.0, handler: nil)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
}
func testThatBackingUpCoreDataCreatesFile() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
self.addObjectsWithNumber(1)
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
sleep(1)
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
}
func testThatBackingUpCoreDataCreatesCorrectFormat() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
let tags = self.addTags()
for i in 1...totalClouds {
self.addObjectsWithNumber(i, tags: tags)
}
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
let url = items[0]
let data = try? Data(contentsOf: url as URL)
var jsonObjects : Any = [:]
if let hasData = data {
do {
jsonObjects = try JSONSerialization.jsonObject(with: hasData, options: JSONSerialization.ReadingOptions.allowFragments)
} catch {
XCTFail("Invalid JSON")
}
} else {
XCTFail("Couldn't read data")
}
XCTAssertEqual((jsonObjects as AnyObject).count, (totalRaindrops * totalClouds) + totalClouds + totalTags)
if let objects = jsonObjects as? [String : AnyObject] {
for (key, value) in objects {
if key.contains("Cloud") {
if let isDict = value as? [String : AnyObject], let type = isDict[StormcloudEntityKeys.EntityType.rawValue] as? String {
XCTAssertEqual(type, "Cloud")
// Assert that the keys exist
XCTAssertNotNil(isDict["order"])
XCTAssertNotNil(isDict["added"])
if let name = isDict["name"] as? String , name == "Cloud 1" {
if let _ = isDict["didRain"] as? Int {
XCTFail("Cloud 1's didRain property should be nil")
} else {
XCTAssertEqual(name, "Cloud 1")
}
}
if let name = isDict["name"] as? String , name == "Cloud 2" {
if let _ = isDict["didRain"] as? Int {
XCTAssertEqual(name, "Cloud 2")
} else {
XCTFail("Cloud 1's didRain property should be set")
}
}
if let value = isDict["chanceOfRain"] as? Float {
XCTAssertEqual(value, 0.45)
} else {
XCTFail("Chance of Rain poperty doesn't exist or is not float")
}
if let relationship = isDict["raindrops"] as? [String] {
XCTAssertEqual(relationship.count, 2)
} else {
XCTFail("Relationship doesn't exist")
}
} else {
XCTFail("Wrong type stored in dictionary")
}
}
if key.contains("Raindrop") {
if let isDict = value as? [String : AnyObject], let type = isDict[StormcloudEntityKeys.EntityType.rawValue] as? String {
XCTAssertEqual(type, "Raindrop")
if let _ = isDict["type"] as? String {
} else {
XCTFail("Type poperty doesn't exist")
}
if let _ = isDict["colour"] as? String {
} else {
XCTFail("Colour poperty doesn't exist")
}
if let value = isDict["timesFallen"] as? NSNumber {
XCTAssertEqual(value, 10)
} else {
XCTFail("Times Fallen poperty doesn't exist or is not number")
}
if let decimalValue = isDict["raindropValue"] as? String {
XCTAssertEqual(decimalValue, "10.54")
} else {
XCTFail("Value poperty doesn't exist or is not number")
}
if let relationship = isDict["cloud"] as? [String] {
XCTAssertEqual(relationship.count, 1)
XCTAssert(relationship[0].contains("Cloud"))
} else {
XCTFail("Relationship doesn't exist")
}
} else {
XCTFail("Wrong type stored in dictionary")
}
}
}
} else {
XCTFail("JSON object invalid")
}
// Read JSON
}
func testThatRestoringRestoresThingsCorrectly() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
waitForFiles(manager)
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
// Give it a chance to catch up
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(1, tags: tags)
self.addObjectsWithNumber(2, tags: tags)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
guard manager.items(for: .json).count > 0 else {
XCTFail("Invalid number of items")
return
}
let exp = self.expectation(description: "Restore expectation")
manager.restoreCoreDataBackup(from: manager.items(for: .json)[0], to: stack.managedObjectContext!) { (success) -> () in
XCTAssertNil(success)
XCTAssertEqual(Thread.current, Thread.main)
exp.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 2)
if clouds.count > 1 {
let cloud1 = clouds[0]
XCTAssertEqual(cloud1.tags?.count, totalTags)
XCTAssertEqual(cloud1.raindrops?.count, totalRaindrops)
XCTAssertEqual(cloud1.name, "Cloud 1")
XCTAssertEqual(cloud1.chanceOfRain?.floatValue, Float( 0.45))
XCTAssertNil(cloud1.didRain)
if let raindrop = cloud1.raindrops?.anyObject() as? Raindrop {
XCTAssertEqual(raindrop.raindropValue?.stringValue, "10.54")
XCTAssertEqual(raindrop.timesFallen, 10)
}
let cloud2 = clouds[1]
XCTAssertEqual(cloud2.tags?.count, totalTags)
if let raindrops = cloud2.raindrops?.allObjects {
XCTAssertEqual(raindrops.count, totalRaindrops)
}
XCTAssertEqual(cloud2.name, "Cloud 2")
XCTAssertEqual(cloud2.chanceOfRain?.floatValue, Float(0.45))
if let bool = cloud2.didRain?.boolValue {
XCTAssert(bool)
}
if let raindrop = cloud2.raindrops?.anyObject() as? Raindrop {
XCTAssertEqual(raindrop.cloud, cloud2)
XCTAssertEqual(raindrop.raindropValue?.stringValue, "10.54")
XCTAssertEqual(raindrop.timesFallen, 10)
}
} else {
XCTFail("Not enough clouds in DB")
}
}
}
func testThatRestoringIndividualItemsWorks() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
self.copyItems(extra: true)
self.setupStack()
let items = self.listItemsAtURL()
waitForFiles(manager)
XCTAssertEqual(items.count, 3)
manager.restoreDelegate = self
guard let context = stack.managedObjectContext else {
XCTFail("Context not ready")
return
}
guard let file = items.filter( { $0.path.contains("fragment") } ).first else {
XCTFail("Couldn't find correct file")
return
}
do {
let jsonData = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
if let isJSON = json as? [String : AnyObject] {
let exp = expectation(description: "Individual Restore Expectation")
manager.insertIndividualObjectsWithContext(context, data: isJSON, completion: { (success) in
guard success else {
XCTFail("Failed to restore objects")
return
}
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
let objects = try! context.fetch(request)
XCTAssertEqual(objects.count, 1)
if let cloud = objects.first {
XCTAssertEqual(cloud.raindrops!.count, 2)
if let raindrops = cloud.raindrops as? Set<Raindrop> {
let heavy = raindrops.filter() { $0.type == "Heavy" }
XCTAssertEqual(heavy.count, 1, "There should be one heavy raindrop")
}
}
exp.fulfill()
})
waitForExpectations(timeout: 3, handler: nil)
} else {
XCTFail("Invalid Format")
}
} catch {
XCTFail("Failed to read contents")
}
}
func testWeirdStrings() {
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 0)
}
if let context = self.stack.managedObjectContext {
do {
_ = try Cloud.insertCloudWithName("\("String \" With 😀🐼🐵⸘&§@$€¥¢£₽₨₩৲₦₴₭₱₮₺฿৳૱௹﷼₹₲₪₡₥₳₤₸₢₵៛₫₠₣₰₧₯₶₷")", order: 0, didRain: true, inContext: context)
} catch {
print("Error inserting cloud")
}
}
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
guard items.count == 1 else {
XCTFail("Incorrect count for items")
return
}
print(manager.urlForItem(manager.items(for: .json)[0]) ?? "No metadata item found")
let expectation = self.expectation(description: "Restore expectation")
manager.restoreCoreDataBackup(from: manager.items(for: .json)[0], to: stack.managedObjectContext!) { (success) -> () in
XCTAssertNil(success)
XCTAssertEqual(Thread.current, Thread.main)
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 1)
if clouds.count == 1 {
let cloud1 = clouds[0]
XCTAssertEqual("\("String \" With 😀🐼🐵⸘&§@$€¥¢£₽₨₩৲₦₴₭₱₮₺฿৳૱௹﷼₹₲₪₡₥₳₤₸₢₵៛₫₠₣₰₧₯₶₷")", cloud1.name)
}
}
}
func stormcloud(stormcloud: Stormcloud, shouldRestore objects: [String : AnyObject], toEntityWithName name: String) -> Bool {
return true
}
}
| mit |
LYM-mg/MGDYZB | MGDYZB/MGDYZB/Class/Home/Controller/FunnyViewController.swift | 1 | 5456 | //
// FunnyViewController.swift
// MGDYZB
//
// Created by ming on 16/10/25.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
import SafariServices
private let kTopMargin : CGFloat = 8
class FunnyViewController: BaseViewController {
// MARK: 懒加载ViewModel对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize.zero
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.scrollsToTop = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: kItemMargin, bottom: kItemMargin, right: kItemMargin)
// 3.注册
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func setUpMainView() {
contentView = collectionView
view.addSubview(collectionView)
super.setUpMainView()
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension FunnyViewController {
func loadData() {
// 1.请求数据
funnyVM.loadFunnyData {
// 1.1.刷新表格
self.collectionView.reloadData()
// 1.2.数据请求完成
self.loadDataFinished()
}
}
}
// MARK: - UICollectionViewDataSource
extension FunnyViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return funnyVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return funnyVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/// 其他组数据
// 1.取出Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
// 2.给cell设置数据
cell.anchor = funnyVM.anchorGroups[(indexPath as NSIndexPath).section].anchors[(indexPath as NSIndexPath).item]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension FunnyViewController: UICollectionViewDelegate {
@objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置数据
headerView.group = funnyVM.anchorGroups[(indexPath as NSIndexPath).section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = funnyVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor)
}
fileprivate func presentShowRoomVc(anchor: AnchorModel) {
if #available(iOS 9.0, *) {
// 1.创建SFSafariViewController
let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
// 2.以Modal方式弹出
present(safariVC, animated: true, completion: nil)
} else {
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
present(webVC, animated: true, completion: nil)
}
}
fileprivate func pushNormalRoomVc(anchor: AnchorModel) {
// 1.创建WebViewController
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
webVC.navigationController?.setNavigationBarHidden(true, animated: true)
// 2.以Push方式弹出
navigationController?.pushViewController(webVC, animated: true)
}
}
| mit |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/generic_existentials/main.swift | 2 | 1131 | class MyClass {
var x: Int
init(_ x: Int) {
self.x = x
}
}
func f<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyClass) x', '(x = 23)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyClass) $R', '(x = 23)'])
}
f(MyClass(23) as Any)
f(MyClass(23) as AnyObject)
func g<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyStruct) x', '(x = 23)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyStruct) $R', '(x = 23)'])
}
struct MyStruct {
var x: Int
init(_ x: Int) {
self.x = x
}
}
g(MyStruct(23) as Any)
func h<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyBigStruct) x', '(x = 23, y = 24, z = 25, w = 26)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyBigStruct) $R', '(x = 23, y = 24, z = 25, w = 26)'])
}
struct MyBigStruct {
var x: Int
var y: Int
var z: Int
var w: Int
init(_ x: Int) {
self.x = x
self.y = x + 1
self.z = x + 2
self.w = x + 3
}
}
h(MyBigStruct(23) as Any)
| apache-2.0 |
BjornRuud/Swiftache | SwiftacheTests/RenderTargetTests.swift | 1 | 1276 | //
// RenderTargetTests.swift
// Swiftache
//
// Copyright (c) 2014 Bjørn Olav Ruud. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE.txt for details.
//
import UIKit
import XCTest
class RenderTargetTests: 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 testStringTarget() {
var parser = newParser("A{{#a}}{{&b}}C{{/a}}")
var b: RenderContext = ["b": "B"]
var a: RenderContext = ["a": b]
parser.parseWithContext(a)
XCTAssertEqual(parser.renderTarget!.text, "ABC")
}
func testFileTarget() {
let url = cachesURL().URLByAppendingPathComponent("file render.html")
var parser = newParser("A{{#a}}{{&b}}C{{/a}}", target: FileRenderTarget(fileURL: url, encoding: NSUTF8StringEncoding))
var b: RenderContext = ["b": "B"]
var a: RenderContext = ["a": b]
parser.parseWithContext(a)
XCTAssertEqual(parser.renderTarget!.text, "ABC")
}
}
| mit |
jasonsturges/swift-prototypes | CollectionViewUsingNIB/CollectionViewUsingNIB/CollectionViewCell.swift | 2 | 280 | //
// CollectionViewCell.swift
// CollectionViewUsingNIB
//
// Created by Jason Sturges on 10/29/15.
// Copyright © 2015 Jason Sturges. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
| mit |
elumalaiIvan/hello-world | TestCoreData/TestCoreData/AppDelegate.swift | 1 | 4616 | //
// AppDelegate.swift
// TestCoreData
//
// Created by Elumalai Ramalingam on 11/05/17.
// Copyright © 2017 Elumalai Ramalingam. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "TestCoreData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit |
ikesyo/swift-corelibs-foundation | TestFoundation/TestNSData.swift | 4 | 221454 | // 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSData: XCTestCase {
class AllOnesImmutableData : NSData {
private var _length : Int
var _pointer : UnsafeMutableBufferPointer<UInt8>? {
willSet {
if let p = _pointer { free(p.baseAddress) }
}
}
init(length: Int) {
_length = length
super.init()
}
required init?(coder aDecoder: NSCoder) {
// Not tested
fatalError()
}
deinit {
if let p = _pointer {
free(p.baseAddress)
}
}
override var length : Int {
get {
return _length
}
}
override var bytes : UnsafeRawPointer {
if let d = _pointer {
return UnsafeRawPointer(d.baseAddress!)
} else {
// Need to allocate the buffer now.
// It doesn't matter if the buffer is uniquely referenced or not here.
let buffer = malloc(length)
memset(buffer!, 1, length)
let bytePtr = buffer!.bindMemory(to: UInt8.self, capacity: length)
let result = UnsafeMutableBufferPointer(start: bytePtr, count: length)
_pointer = result
return UnsafeRawPointer(result.baseAddress!)
}
}
override func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) {
if let d = _pointer {
// Get the real data from the buffer
memmove(buffer, d.baseAddress!, length)
} else {
// A more efficient implementation of getBytes in the case where no one has asked for our backing bytes
memset(buffer, 1, length)
}
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return AllOnesData(length: _length)
}
}
class AllOnesData : NSMutableData {
private var _length : Int
var _pointer : UnsafeMutableBufferPointer<UInt8>? {
willSet {
if let p = _pointer { free(p.baseAddress) }
}
}
override init(length: Int) {
_length = length
super.init()
}
required init?(coder aDecoder: NSCoder) {
// Not tested
fatalError()
}
deinit {
if let p = _pointer {
free(p.baseAddress)
}
}
override var length : Int {
get {
return _length
}
set {
if let ptr = _pointer {
// Copy the data to our new length buffer
let newBuffer = malloc(newValue)!
if newValue <= _length {
memmove(newBuffer, ptr.baseAddress!, newValue)
} else if newValue > _length {
memmove(newBuffer, ptr.baseAddress!, _length)
memset(newBuffer + _length, 1, newValue - _length)
}
let bytePtr = newBuffer.bindMemory(to: UInt8.self, capacity: newValue)
_pointer = UnsafeMutableBufferPointer(start: bytePtr, count: newValue)
}
_length = newValue
}
}
override var bytes : UnsafeRawPointer {
if let d = _pointer {
return UnsafeRawPointer(d.baseAddress!)
} else {
// Need to allocate the buffer now.
// It doesn't matter if the buffer is uniquely referenced or not here.
let buffer = malloc(length)
memset(buffer!, 1, length)
let bytePtr = buffer!.bindMemory(to: UInt8.self, capacity: length)
let result = UnsafeMutableBufferPointer(start: bytePtr, count: length)
_pointer = result
return UnsafeRawPointer(result.baseAddress!)
}
}
override var mutableBytes: UnsafeMutableRawPointer {
let newBufferLength = _length
let newBuffer = malloc(newBufferLength)
if let ptr = _pointer {
// Copy the existing data to the new box, then return its pointer
memmove(newBuffer!, ptr.baseAddress!, newBufferLength)
} else {
// Set new data to 1s
memset(newBuffer!, 1, newBufferLength)
}
let bytePtr = newBuffer!.bindMemory(to: UInt8.self, capacity: newBufferLength)
let result = UnsafeMutableBufferPointer(start: bytePtr, count: newBufferLength)
_pointer = result
_length = newBufferLength
return UnsafeMutableRawPointer(result.baseAddress!)
}
override func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) {
if let d = _pointer {
// Get the real data from the buffer
memmove(buffer, d.baseAddress!, length)
} else {
// A more efficient implementation of getBytes in the case where no one has asked for our backing bytes
memset(buffer, 1, length)
}
}
}
var heldData: Data?
// this holds a reference while applying the function which forces the internal ref type to become non-uniquely referenced
func holdReference(_ data: Data, apply: () -> Void) {
heldData = data
apply()
heldData = nil
}
// MARK: -
// String of course has its own way to get data, but this way tests our own data struct
func dataFrom(_ string : String) -> Data {
// Create a Data out of those bytes
return string.utf8CString.withUnsafeBufferPointer { (ptr) in
ptr.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: ptr.count) {
// Subtract 1 so we don't get the null terminator byte. This matches NSString behavior.
return Data(bytes: $0, count: ptr.count - 1)
}
}
}
static var allTests: [(String, (TestNSData) -> () throws -> Void)] {
return [
("testBasicConstruction", testBasicConstruction),
("test_base64Data_medium", test_base64Data_medium),
("test_base64Data_small", test_base64Data_small),
("test_openingNonExistentFile", test_openingNonExistentFile),
("test_contentsOfFile", test_contentsOfFile),
("test_contentsOfZeroFile", test_contentsOfZeroFile),
("test_basicReadWrite", test_basicReadWrite),
("test_bufferSizeCalculation", test_bufferSizeCalculation),
("test_dataHash", test_dataHash),
("test_genericBuffers", test_genericBuffers),
("test_writeFailure", test_writeFailure),
("testBridgingDefault", testBridgingDefault),
("testBridgingMutable", testBridgingMutable),
("testCopyBytes_oversized", testCopyBytes_oversized),
("testCopyBytes_ranges", testCopyBytes_ranges),
("testCopyBytes_undersized", testCopyBytes_undersized),
("testCopyBytes", testCopyBytes),
("testCustomDeallocator", testCustomDeallocator),
("testDataInSet", testDataInSet),
("testEquality", testEquality),
("testGenericAlgorithms", testGenericAlgorithms),
("testInitializationWithArray", testInitializationWithArray),
("testInsertData", testInsertData),
("testLoops", testLoops),
("testMutableData", testMutableData),
("testRange", testRange),
("testReplaceSubrange", testReplaceSubrange),
("testReplaceSubrange2", testReplaceSubrange2),
("testReplaceSubrange3", testReplaceSubrange3),
("testReplaceSubrange4", testReplaceSubrange4),
("testReplaceSubrange5", testReplaceSubrange5),
("test_description", test_description),
("test_emptyDescription", test_emptyDescription),
("test_longDescription", test_longDescription),
("test_debugDescription", test_debugDescription),
("test_longDebugDescription", test_longDebugDescription),
("test_limitDebugDescription", test_limitDebugDescription),
("test_edgeDebugDescription", test_edgeDebugDescription),
("test_writeToURLOptions", test_writeToURLOptions),
("test_edgeNoCopyDescription", test_edgeNoCopyDescription),
("test_initializeWithBase64EncodedDataGetsDecodedData", test_initializeWithBase64EncodedDataGetsDecodedData),
("test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil", test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil),
("test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter", test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter),
("test_base64EncodedDataGetsEncodedText", test_base64EncodedDataGetsEncodedText),
("test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn", test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn),
("test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed", test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed),
("test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth", test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth),
("test_base64EncodedStringGetsEncodedText", test_base64EncodedStringGetsEncodedText),
("test_initializeWithBase64EncodedStringGetsDecodedData", test_initializeWithBase64EncodedStringGetsDecodedData),
("test_base64DecodeWithPadding1", test_base64DecodeWithPadding1),
("test_base64DecodeWithPadding2", test_base64DecodeWithPadding2),
("test_rangeOfData", test_rangeOfData),
("test_initNSMutableData()", test_initNSMutableData),
("test_initNSMutableDataWithLength", test_initNSMutableDataWithLength),
("test_initNSMutableDataWithCapacity", test_initNSMutableDataWithCapacity),
("test_initNSMutableDataFromData", test_initNSMutableDataFromData),
("test_initNSMutableDataFromBytes", test_initNSMutableDataFromBytes),
("test_initNSMutableDataContentsOf", test_initNSMutableDataContentsOf),
("test_initNSMutableDataBase64", test_initNSMutableDataBase64),
("test_replaceBytes", test_replaceBytes),
("test_replaceBytesWithNil", test_replaceBytesWithNil),
("test_initDataWithCapacity", test_initDataWithCapacity),
("test_initDataWithCount", test_initDataWithCount),
("test_emptyStringToData", test_emptyStringToData),
("test_repeatingValueInitialization", test_repeatingValueInitialization),
("test_sliceAppending", test_sliceAppending),
("test_replaceSubrange", test_replaceSubrange),
("test_sliceWithUnsafeBytes", test_sliceWithUnsafeBytes),
("test_sliceIteration", test_sliceIteration),
("test_validateMutation_withUnsafeMutableBytes", test_validateMutation_withUnsafeMutableBytes),
("test_validateMutation_appendBytes", test_validateMutation_appendBytes),
("test_validateMutation_appendData", test_validateMutation_appendData),
("test_validateMutation_appendBuffer", test_validateMutation_appendBuffer),
("test_validateMutation_appendSequence", test_validateMutation_appendSequence),
("test_validateMutation_appendContentsOf", test_validateMutation_appendContentsOf),
("test_validateMutation_resetBytes", test_validateMutation_resetBytes),
("test_validateMutation_replaceSubrange", test_validateMutation_replaceSubrange),
("test_validateMutation_replaceSubrangeCountableRange", test_validateMutation_replaceSubrangeCountableRange),
("test_validateMutation_replaceSubrangeWithBuffer", test_validateMutation_replaceSubrangeWithBuffer),
("test_validateMutation_replaceSubrangeWithCollection", test_validateMutation_replaceSubrangeWithCollection),
("test_validateMutation_replaceSubrangeWithBytes", test_validateMutation_replaceSubrangeWithBytes),
("test_validateMutation_slice_withUnsafeMutableBytes", test_validateMutation_slice_withUnsafeMutableBytes),
("test_validateMutation_slice_appendBytes", test_validateMutation_slice_appendBytes),
("test_validateMutation_slice_appendData", test_validateMutation_slice_appendData),
("test_validateMutation_slice_appendBuffer", test_validateMutation_slice_appendBuffer),
("test_validateMutation_slice_appendSequence", test_validateMutation_slice_appendSequence),
("test_validateMutation_slice_appendContentsOf", test_validateMutation_slice_appendContentsOf),
("test_validateMutation_slice_resetBytes", test_validateMutation_slice_resetBytes),
("test_validateMutation_slice_replaceSubrange", test_validateMutation_slice_replaceSubrange),
("test_validateMutation_slice_replaceSubrangeCountableRange", test_validateMutation_slice_replaceSubrangeCountableRange),
("test_validateMutation_slice_replaceSubrangeWithBuffer", test_validateMutation_slice_replaceSubrangeWithBuffer),
("test_validateMutation_slice_replaceSubrangeWithCollection", test_validateMutation_slice_replaceSubrangeWithCollection),
("test_validateMutation_slice_replaceSubrangeWithBytes", test_validateMutation_slice_replaceSubrangeWithBytes),
("test_validateMutation_cow_withUnsafeMutableBytes", test_validateMutation_cow_withUnsafeMutableBytes),
("test_validateMutation_cow_appendBytes", test_validateMutation_cow_appendBytes),
("test_validateMutation_cow_appendData", test_validateMutation_cow_appendData),
("test_validateMutation_cow_appendBuffer", test_validateMutation_cow_appendBuffer),
("test_validateMutation_cow_appendSequence", test_validateMutation_cow_appendSequence),
("test_validateMutation_cow_appendContentsOf", test_validateMutation_cow_appendContentsOf),
("test_validateMutation_cow_resetBytes", test_validateMutation_cow_resetBytes),
("test_validateMutation_cow_replaceSubrange", test_validateMutation_cow_replaceSubrange),
("test_validateMutation_cow_replaceSubrangeCountableRange", test_validateMutation_cow_replaceSubrangeCountableRange),
("test_validateMutation_cow_replaceSubrangeWithBuffer", test_validateMutation_cow_replaceSubrangeWithBuffer),
("test_validateMutation_cow_replaceSubrangeWithCollection", test_validateMutation_cow_replaceSubrangeWithCollection),
("test_validateMutation_cow_replaceSubrangeWithBytes", test_validateMutation_cow_replaceSubrangeWithBytes),
("test_validateMutation_slice_cow_withUnsafeMutableBytes", test_validateMutation_slice_cow_withUnsafeMutableBytes),
("test_validateMutation_slice_cow_appendBytes", test_validateMutation_slice_cow_appendBytes),
("test_validateMutation_slice_cow_appendData", test_validateMutation_slice_cow_appendData),
("test_validateMutation_slice_cow_appendBuffer", test_validateMutation_slice_cow_appendBuffer),
("test_validateMutation_slice_cow_appendSequence", test_validateMutation_slice_cow_appendSequence),
("test_validateMutation_slice_cow_appendContentsOf", test_validateMutation_slice_cow_appendContentsOf),
("test_validateMutation_slice_cow_resetBytes", test_validateMutation_slice_cow_resetBytes),
("test_validateMutation_slice_cow_replaceSubrange", test_validateMutation_slice_cow_replaceSubrange),
("test_validateMutation_slice_cow_replaceSubrangeCountableRange", test_validateMutation_slice_cow_replaceSubrangeCountableRange),
("test_validateMutation_slice_cow_replaceSubrangeWithBuffer", test_validateMutation_slice_cow_replaceSubrangeWithBuffer),
("test_validateMutation_slice_cow_replaceSubrangeWithCollection", test_validateMutation_slice_cow_replaceSubrangeWithCollection),
("test_validateMutation_slice_cow_replaceSubrangeWithBytes", test_validateMutation_slice_cow_replaceSubrangeWithBytes),
("test_validateMutation_immutableBacking_withUnsafeMutableBytes", test_validateMutation_immutableBacking_withUnsafeMutableBytes),
("test_validateMutation_immutableBacking_appendBytes", test_validateMutation_immutableBacking_appendBytes),
("test_validateMutation_immutableBacking_appendData", test_validateMutation_immutableBacking_appendData),
("test_validateMutation_immutableBacking_appendBuffer", test_validateMutation_immutableBacking_appendBuffer),
("test_validateMutation_immutableBacking_appendSequence", test_validateMutation_immutableBacking_appendSequence),
("test_validateMutation_immutableBacking_appendContentsOf", test_validateMutation_immutableBacking_appendContentsOf),
("test_validateMutation_immutableBacking_resetBytes", test_validateMutation_immutableBacking_resetBytes),
("test_validateMutation_immutableBacking_replaceSubrange", test_validateMutation_immutableBacking_replaceSubrange),
("test_validateMutation_immutableBacking_replaceSubrangeCountableRange", test_validateMutation_immutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_immutableBacking_replaceSubrangeWithBuffer", test_validateMutation_immutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_immutableBacking_replaceSubrangeWithCollection", test_validateMutation_immutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_immutableBacking_replaceSubrangeWithBytes", test_validateMutation_immutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes),
("test_validateMutation_slice_immutableBacking_appendBytes", test_validateMutation_slice_immutableBacking_appendBytes),
("test_validateMutation_slice_immutableBacking_appendData", test_validateMutation_slice_immutableBacking_appendData),
("test_validateMutation_slice_immutableBacking_appendBuffer", test_validateMutation_slice_immutableBacking_appendBuffer),
("test_validateMutation_slice_immutableBacking_appendSequence", test_validateMutation_slice_immutableBacking_appendSequence),
("test_validateMutation_slice_immutableBacking_appendContentsOf", test_validateMutation_slice_immutableBacking_appendContentsOf),
("test_validateMutation_slice_immutableBacking_resetBytes", test_validateMutation_slice_immutableBacking_resetBytes),
("test_validateMutation_slice_immutableBacking_replaceSubrange", test_validateMutation_slice_immutableBacking_replaceSubrange),
("test_validateMutation_slice_immutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_immutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_slice_immutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_immutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_slice_immutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_immutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_slice_immutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_immutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_cow_immutableBacking_withUnsafeMutableBytes", test_validateMutation_cow_immutableBacking_withUnsafeMutableBytes),
("test_validateMutation_cow_immutableBacking_appendBytes", test_validateMutation_cow_immutableBacking_appendBytes),
("test_validateMutation_cow_immutableBacking_appendData", test_validateMutation_cow_immutableBacking_appendData),
("test_validateMutation_cow_immutableBacking_appendBuffer", test_validateMutation_cow_immutableBacking_appendBuffer),
("test_validateMutation_cow_immutableBacking_appendSequence", test_validateMutation_cow_immutableBacking_appendSequence),
("test_validateMutation_cow_immutableBacking_appendContentsOf", test_validateMutation_cow_immutableBacking_appendContentsOf),
("test_validateMutation_cow_immutableBacking_resetBytes", test_validateMutation_cow_immutableBacking_resetBytes),
("test_validateMutation_cow_immutableBacking_replaceSubrange", test_validateMutation_cow_immutableBacking_replaceSubrange),
("test_validateMutation_cow_immutableBacking_replaceSubrangeCountableRange", test_validateMutation_cow_immutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_cow_immutableBacking_replaceSubrangeWithBuffer", test_validateMutation_cow_immutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_cow_immutableBacking_replaceSubrangeWithCollection", test_validateMutation_cow_immutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_cow_immutableBacking_replaceSubrangeWithBytes", test_validateMutation_cow_immutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_slice_cow_immutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_cow_immutableBacking_withUnsafeMutableBytes),
("test_validateMutation_slice_cow_immutableBacking_appendBytes", test_validateMutation_slice_cow_immutableBacking_appendBytes),
("test_validateMutation_slice_cow_immutableBacking_appendData", test_validateMutation_slice_cow_immutableBacking_appendData),
("test_validateMutation_slice_cow_immutableBacking_appendBuffer", test_validateMutation_slice_cow_immutableBacking_appendBuffer),
("test_validateMutation_slice_cow_immutableBacking_appendSequence", test_validateMutation_slice_cow_immutableBacking_appendSequence),
("test_validateMutation_slice_cow_immutableBacking_appendContentsOf", test_validateMutation_slice_cow_immutableBacking_appendContentsOf),
("test_validateMutation_slice_cow_immutableBacking_resetBytes", test_validateMutation_slice_cow_immutableBacking_resetBytes),
("test_validateMutation_slice_cow_immutableBacking_replaceSubrange", test_validateMutation_slice_cow_immutableBacking_replaceSubrange),
("test_validateMutation_slice_cow_immutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_cow_immutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_mutableBacking_withUnsafeMutableBytes", test_validateMutation_mutableBacking_withUnsafeMutableBytes),
("test_validateMutation_mutableBacking_appendBytes", test_validateMutation_mutableBacking_appendBytes),
("test_validateMutation_mutableBacking_appendData", test_validateMutation_mutableBacking_appendData),
("test_validateMutation_mutableBacking_appendBuffer", test_validateMutation_mutableBacking_appendBuffer),
("test_validateMutation_mutableBacking_appendSequence", test_validateMutation_mutableBacking_appendSequence),
("test_validateMutation_mutableBacking_appendContentsOf", test_validateMutation_mutableBacking_appendContentsOf),
("test_validateMutation_mutableBacking_resetBytes", test_validateMutation_mutableBacking_resetBytes),
("test_validateMutation_mutableBacking_replaceSubrange", test_validateMutation_mutableBacking_replaceSubrange),
("test_validateMutation_mutableBacking_replaceSubrangeCountableRange", test_validateMutation_mutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_mutableBacking_replaceSubrangeWithBuffer", test_validateMutation_mutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_mutableBacking_replaceSubrangeWithCollection", test_validateMutation_mutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_mutableBacking_replaceSubrangeWithBytes", test_validateMutation_mutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes),
("test_validateMutation_slice_mutableBacking_appendBytes", test_validateMutation_slice_mutableBacking_appendBytes),
("test_validateMutation_slice_mutableBacking_appendData", test_validateMutation_slice_mutableBacking_appendData),
("test_validateMutation_slice_mutableBacking_appendBuffer", test_validateMutation_slice_mutableBacking_appendBuffer),
("test_validateMutation_slice_mutableBacking_appendSequence", test_validateMutation_slice_mutableBacking_appendSequence),
("test_validateMutation_slice_mutableBacking_appendContentsOf", test_validateMutation_slice_mutableBacking_appendContentsOf),
("test_validateMutation_slice_mutableBacking_resetBytes", test_validateMutation_slice_mutableBacking_resetBytes),
("test_validateMutation_slice_mutableBacking_replaceSubrange", test_validateMutation_slice_mutableBacking_replaceSubrange),
("test_validateMutation_slice_mutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_mutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_slice_mutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_mutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_slice_mutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_mutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_slice_mutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_mutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_cow_mutableBacking_withUnsafeMutableBytes", test_validateMutation_cow_mutableBacking_withUnsafeMutableBytes),
("test_validateMutation_cow_mutableBacking_appendBytes", test_validateMutation_cow_mutableBacking_appendBytes),
("test_validateMutation_cow_mutableBacking_appendData", test_validateMutation_cow_mutableBacking_appendData),
("test_validateMutation_cow_mutableBacking_appendBuffer", test_validateMutation_cow_mutableBacking_appendBuffer),
("test_validateMutation_cow_mutableBacking_appendSequence", test_validateMutation_cow_mutableBacking_appendSequence),
("test_validateMutation_cow_mutableBacking_appendContentsOf", test_validateMutation_cow_mutableBacking_appendContentsOf),
("test_validateMutation_cow_mutableBacking_resetBytes", test_validateMutation_cow_mutableBacking_resetBytes),
("test_validateMutation_cow_mutableBacking_replaceSubrange", test_validateMutation_cow_mutableBacking_replaceSubrange),
("test_validateMutation_cow_mutableBacking_replaceSubrangeCountableRange", test_validateMutation_cow_mutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_cow_mutableBacking_replaceSubrangeWithBuffer", test_validateMutation_cow_mutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_cow_mutableBacking_replaceSubrangeWithCollection", test_validateMutation_cow_mutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_cow_mutableBacking_replaceSubrangeWithBytes", test_validateMutation_cow_mutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_slice_cow_mutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_cow_mutableBacking_withUnsafeMutableBytes),
("test_validateMutation_slice_cow_mutableBacking_appendBytes", test_validateMutation_slice_cow_mutableBacking_appendBytes),
("test_validateMutation_slice_cow_mutableBacking_appendData", test_validateMutation_slice_cow_mutableBacking_appendData),
("test_validateMutation_slice_cow_mutableBacking_appendBuffer", test_validateMutation_slice_cow_mutableBacking_appendBuffer),
("test_validateMutation_slice_cow_mutableBacking_appendSequence", test_validateMutation_slice_cow_mutableBacking_appendSequence),
("test_validateMutation_slice_cow_mutableBacking_appendContentsOf", test_validateMutation_slice_cow_mutableBacking_appendContentsOf),
("test_validateMutation_slice_cow_mutableBacking_resetBytes", test_validateMutation_slice_cow_mutableBacking_resetBytes),
("test_validateMutation_slice_cow_mutableBacking_replaceSubrange", test_validateMutation_slice_cow_mutableBacking_replaceSubrange),
("test_validateMutation_slice_cow_mutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_cow_mutableBacking_replaceSubrangeCountableRange),
("test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBuffer),
("test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithCollection),
("test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBytes),
("test_validateMutation_customBacking_withUnsafeMutableBytes", test_validateMutation_customBacking_withUnsafeMutableBytes),
// ("test_validateMutation_customBacking_appendBytes", test_validateMutation_customBacking_appendBytes),
// ("test_validateMutation_customBacking_appendData", test_validateMutation_customBacking_appendData),
// ("test_validateMutation_customBacking_appendBuffer", test_validateMutation_customBacking_appendBuffer),
// ("test_validateMutation_customBacking_appendSequence", test_validateMutation_customBacking_appendSequence),
// ("test_validateMutation_customBacking_appendContentsOf", test_validateMutation_customBacking_appendContentsOf),
// ("test_validateMutation_customBacking_resetBytes", test_validateMutation_customBacking_resetBytes),
// ("test_validateMutation_customBacking_replaceSubrange", test_validateMutation_customBacking_replaceSubrange),
// ("test_validateMutation_customBacking_replaceSubrangeCountableRange", test_validateMutation_customBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_customBacking_replaceSubrangeWithBuffer", test_validateMutation_customBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_customBacking_replaceSubrangeWithCollection", test_validateMutation_customBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_customBacking_replaceSubrangeWithBytes", test_validateMutation_customBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_slice_customBacking_withUnsafeMutableBytes", test_validateMutation_slice_customBacking_withUnsafeMutableBytes),
// ("test_validateMutation_slice_customBacking_appendBytes", test_validateMutation_slice_customBacking_appendBytes),
// ("test_validateMutation_slice_customBacking_appendData", test_validateMutation_slice_customBacking_appendData),
// ("test_validateMutation_slice_customBacking_appendBuffer", test_validateMutation_slice_customBacking_appendBuffer),
// ("test_validateMutation_slice_customBacking_appendSequence", test_validateMutation_slice_customBacking_appendSequence),
// ("test_validateMutation_slice_customBacking_appendContentsOf", test_validateMutation_slice_customBacking_appendContentsOf),
// ("test_validateMutation_slice_customBacking_resetBytes", test_validateMutation_slice_customBacking_resetBytes),
// ("test_validateMutation_slice_customBacking_replaceSubrange", test_validateMutation_slice_customBacking_replaceSubrange),
// ("test_validateMutation_slice_customBacking_replaceSubrangeCountableRange", test_validateMutation_slice_customBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_slice_customBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_customBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_slice_customBacking_replaceSubrangeWithCollection", test_validateMutation_slice_customBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_slice_customBacking_replaceSubrangeWithBytes", test_validateMutation_slice_customBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_cow_customBacking_withUnsafeMutableBytes", test_validateMutation_cow_customBacking_withUnsafeMutableBytes),
// ("test_validateMutation_cow_customBacking_appendBytes", test_validateMutation_cow_customBacking_appendBytes),
// ("test_validateMutation_cow_customBacking_appendData", test_validateMutation_cow_customBacking_appendData),
// ("test_validateMutation_cow_customBacking_appendBuffer", test_validateMutation_cow_customBacking_appendBuffer),
// ("test_validateMutation_cow_customBacking_appendSequence", test_validateMutation_cow_customBacking_appendSequence),
// ("test_validateMutation_cow_customBacking_appendContentsOf", test_validateMutation_cow_customBacking_appendContentsOf),
// ("test_validateMutation_cow_customBacking_resetBytes", test_validateMutation_cow_customBacking_resetBytes),
// ("test_validateMutation_cow_customBacking_replaceSubrange", test_validateMutation_cow_customBacking_replaceSubrange),
// ("test_validateMutation_cow_customBacking_replaceSubrangeCountableRange", test_validateMutation_cow_customBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_cow_customBacking_replaceSubrangeWithBuffer", test_validateMutation_cow_customBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_cow_customBacking_replaceSubrangeWithCollection", test_validateMutation_cow_customBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_cow_customBacking_replaceSubrangeWithBytes", test_validateMutation_cow_customBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_slice_cow_customBacking_withUnsafeMutableBytes", test_validateMutation_slice_cow_customBacking_withUnsafeMutableBytes),
// ("test_validateMutation_slice_cow_customBacking_appendBytes", test_validateMutation_slice_cow_customBacking_appendBytes),
// ("test_validateMutation_slice_cow_customBacking_appendData", test_validateMutation_slice_cow_customBacking_appendData),
// ("test_validateMutation_slice_cow_customBacking_appendBuffer", test_validateMutation_slice_cow_customBacking_appendBuffer),
// ("test_validateMutation_slice_cow_customBacking_appendSequence", test_validateMutation_slice_cow_customBacking_appendSequence),
// ("test_validateMutation_slice_cow_customBacking_appendContentsOf", test_validateMutation_slice_cow_customBacking_appendContentsOf),
// ("test_validateMutation_slice_cow_customBacking_resetBytes", test_validateMutation_slice_cow_customBacking_resetBytes),
// ("test_validateMutation_slice_cow_customBacking_replaceSubrange", test_validateMutation_slice_cow_customBacking_replaceSubrange),
// ("test_validateMutation_slice_cow_customBacking_replaceSubrangeCountableRange", test_validateMutation_slice_cow_customBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_slice_cow_customBacking_replaceSubrangeWithCollection", test_validateMutation_slice_cow_customBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBytes", test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_customMutableBacking_withUnsafeMutableBytes", test_validateMutation_customMutableBacking_withUnsafeMutableBytes),
// ("test_validateMutation_customMutableBacking_appendBytes", test_validateMutation_customMutableBacking_appendBytes),
// ("test_validateMutation_customMutableBacking_appendData", test_validateMutation_customMutableBacking_appendData),
// ("test_validateMutation_customMutableBacking_appendBuffer", test_validateMutation_customMutableBacking_appendBuffer),
// ("test_validateMutation_customMutableBacking_appendSequence", test_validateMutation_customMutableBacking_appendSequence),
// ("test_validateMutation_customMutableBacking_appendContentsOf", test_validateMutation_customMutableBacking_appendContentsOf),
// ("test_validateMutation_customMutableBacking_resetBytes", test_validateMutation_customMutableBacking_resetBytes),
// ("test_validateMutation_customMutableBacking_replaceSubrange", test_validateMutation_customMutableBacking_replaceSubrange),
// ("test_validateMutation_customMutableBacking_replaceSubrangeCountableRange", test_validateMutation_customMutableBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_customMutableBacking_replaceSubrangeWithBuffer", test_validateMutation_customMutableBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_customMutableBacking_replaceSubrangeWithCollection", test_validateMutation_customMutableBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_customMutableBacking_replaceSubrangeWithBytes", test_validateMutation_customMutableBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes),
// ("test_validateMutation_slice_customMutableBacking_appendBytes", test_validateMutation_slice_customMutableBacking_appendBytes),
// ("test_validateMutation_slice_customMutableBacking_appendData", test_validateMutation_slice_customMutableBacking_appendData),
// ("test_validateMutation_slice_customMutableBacking_appendBuffer", test_validateMutation_slice_customMutableBacking_appendBuffer),
// ("test_validateMutation_slice_customMutableBacking_appendSequence", test_validateMutation_slice_customMutableBacking_appendSequence),
// ("test_validateMutation_slice_customMutableBacking_appendContentsOf", test_validateMutation_slice_customMutableBacking_appendContentsOf),
// ("test_validateMutation_slice_customMutableBacking_resetBytes", test_validateMutation_slice_customMutableBacking_resetBytes),
// ("test_validateMutation_slice_customMutableBacking_replaceSubrange", test_validateMutation_slice_customMutableBacking_replaceSubrange),
// ("test_validateMutation_slice_customMutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_customMutableBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_slice_customMutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_customMutableBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_cow_customMutableBacking_withUnsafeMutableBytes", test_validateMutation_cow_customMutableBacking_withUnsafeMutableBytes),
// ("test_validateMutation_cow_customMutableBacking_appendBytes", test_validateMutation_cow_customMutableBacking_appendBytes),
// ("test_validateMutation_cow_customMutableBacking_appendData", test_validateMutation_cow_customMutableBacking_appendData),
// ("test_validateMutation_cow_customMutableBacking_appendBuffer", test_validateMutation_cow_customMutableBacking_appendBuffer),
// ("test_validateMutation_cow_customMutableBacking_appendSequence", test_validateMutation_cow_customMutableBacking_appendSequence),
// ("test_validateMutation_cow_customMutableBacking_appendContentsOf", test_validateMutation_cow_customMutableBacking_appendContentsOf),
// ("test_validateMutation_cow_customMutableBacking_resetBytes", test_validateMutation_cow_customMutableBacking_resetBytes),
// ("test_validateMutation_cow_customMutableBacking_replaceSubrange", test_validateMutation_cow_customMutableBacking_replaceSubrange),
// ("test_validateMutation_cow_customMutableBacking_replaceSubrangeCountableRange", test_validateMutation_cow_customMutableBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBuffer", test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_cow_customMutableBacking_replaceSubrangeWithCollection", test_validateMutation_cow_customMutableBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBytes", test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBytes),
// ("test_validateMutation_slice_cow_customMutableBacking_withUnsafeMutableBytes", test_validateMutation_slice_cow_customMutableBacking_withUnsafeMutableBytes),
// ("test_validateMutation_slice_cow_customMutableBacking_appendBytes", test_validateMutation_slice_cow_customMutableBacking_appendBytes),
// ("test_validateMutation_slice_cow_customMutableBacking_appendData", test_validateMutation_slice_cow_customMutableBacking_appendData),
// ("test_validateMutation_slice_cow_customMutableBacking_appendBuffer", test_validateMutation_slice_cow_customMutableBacking_appendBuffer),
// ("test_validateMutation_slice_cow_customMutableBacking_appendSequence", test_validateMutation_slice_cow_customMutableBacking_appendSequence),
// ("test_validateMutation_slice_cow_customMutableBacking_appendContentsOf", test_validateMutation_slice_cow_customMutableBacking_appendContentsOf),
// ("test_validateMutation_slice_cow_customMutableBacking_resetBytes", test_validateMutation_slice_cow_customMutableBacking_resetBytes),
// ("test_validateMutation_slice_cow_customMutableBacking_replaceSubrange", test_validateMutation_slice_cow_customMutableBacking_replaceSubrange),
// ("test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeCountableRange", test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeCountableRange),
// ("test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBuffer", test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBuffer),
// ("test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithCollection", test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithCollection),
// ("test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBytes", test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBytes),
("test_sliceHash", test_sliceHash),
("test_slice_resize_growth", test_slice_resize_growth),
// ("test_sliceEnumeration", test_sliceEnumeration),
("test_sliceInsertion", test_sliceInsertion),
("test_sliceDeletion", test_sliceDeletion),
("test_validateMutation_slice_withUnsafeMutableBytes_lengthLessThanLowerBound", test_validateMutation_slice_withUnsafeMutableBytes_lengthLessThanLowerBound),
("test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound", test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
("test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound", test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
("test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound", test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
("test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound",
test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
]
}
func test_writeToURLOptions() {
let saveData = try! Data(contentsOf: testBundle().url(forResource: "Test", withExtension: "plist")!)
let savePath = URL(fileURLWithPath: NSTemporaryDirectory() + "Test1.plist")
do {
try saveData.write(to: savePath, options: .atomic)
let fileManager = FileManager.default
XCTAssertTrue(fileManager.fileExists(atPath: savePath.path))
try! fileManager.removeItem(atPath: savePath.path)
} catch _ {
XCTFail()
}
}
func test_emptyDescription() {
let expected = "<>"
let bytes: [UInt8] = []
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(expected, data.description)
}
func test_description() {
let expected = "<ff4c3e00 55>"
let bytes: [UInt8] = [0xff, 0x4c, 0x3e, 0x00, 0x55]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.description, expected)
}
func test_longDescription() {
// taken directly from Foundation
let expected = "<ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8>"
let bytes: [UInt8] = [0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, ]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(expected, data.description)
}
func test_debugDescription() {
let expected = "<ff4c3e00 55>"
let bytes: [UInt8] = [0xff, 0x4c, 0x3e, 0x00, 0x55]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_limitDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff>"
let bytes = [UInt8](repeating: 0xff, count: 1024)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_longDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff>"
let bytes = [UInt8](repeating: 0xff, count: 100_000)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_edgeDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ff>"
let bytes = [UInt8](repeating: 0xff, count: 1025)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_edgeNoCopyDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ff>"
let bytes = [UInt8](repeating: 0xff, count: 1025)
let data = NSData(bytesNoCopy: UnsafeMutablePointer(mutating: bytes), length: bytes.count, freeWhenDone: false)
XCTAssertEqual(data.debugDescription, expected)
XCTAssertEqual(data.bytes, bytes)
}
func test_initializeWithBase64EncodedDataGetsDecodedData() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHByaW11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
guard let decodedData = Data(base64Encoded: encodedData, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
XCTAssertTrue(decodedData == plainText.data(using: .utf8)!)
}
func test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil() {
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHBya$W11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
let decodedData = NSData(base64Encoded: encodedData, options: [])
XCTAssertNil(decodedData)
}
func test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHBya$W11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
guard let decodedData = Data(base64Encoded: encodedData, options: [.ignoreUnknownCharacters]) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
XCTAssertTrue(decodedData == plainText.data(using: .utf8)!)
}
func test_initializeWithBase64EncodedStringGetsDecodedData() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHByaW11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let decodedData = Data(base64Encoded: encodedText, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
}
func test_base64EncodedDataGetsEncodedText() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1aXQgYEFjaGF0ZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVuYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData()
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1\naXQgYEFjaGF0ZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVu\nYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength64Characters, .endLineWithLineFeed])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1aXQgYEFjaGF0\rZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVuYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength76Characters, .endLineWithCarriageReturn])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth() {
let plainText = "Revocate animos, maestumque timorem mittite: forsan et haec olim meminisse iuvabit."
let encodedText = "UmV2b2NhdGUgYW5pbW9zLCBtYWVzdHVtcXVlIHRpbW9yZW0gbWl0dGl0ZTogZm9yc2FuIGV0IGhh\r\nZWMgb2xpbSBtZW1pbmlzc2UgaXV2YWJpdC4="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength76Characters, .endLineWithCarriageReturn, .endLineWithLineFeed])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedStringGetsEncodedText() {
let plainText = "Revocate animos, maestumque timorem mittite: forsan et haec olim meminisse iuvabit."
let encodedText = "UmV2b2NhdGUgYW5pbW9zLCBtYWVzdHVtcXVlIHRpbW9yZW0gbWl0dGl0ZTogZm9yc2FuIGV0IGhhZWMgb2xpbSBtZW1pbmlzc2UgaXV2YWJpdC4="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedTextResult = data.base64EncodedString()
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64DecodeWithPadding1() {
let encodedPadding1 = "AoR="
let dataPadding1Bytes : [UInt8] = [0x02,0x84]
let dataPadding1 = NSData(bytes: dataPadding1Bytes, length: dataPadding1Bytes.count)
guard let decodedPadding1 = Data(base64Encoded:encodedPadding1, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
XCTAssert(dataPadding1.isEqual(to: decodedPadding1))
}
func test_base64DecodeWithPadding2() {
let encodedPadding2 = "Ao=="
let dataPadding2Bytes : [UInt8] = [0x02]
let dataPadding2 = NSData(bytes: dataPadding2Bytes, length: dataPadding2Bytes.count)
guard let decodedPadding2 = Data(base64Encoded:encodedPadding2, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
XCTAssert(dataPadding2.isEqual(to: decodedPadding2))
}
func test_rangeOfData() {
let baseData : [UInt8] = [0x00,0x01,0x02,0x03,0x04]
let base = NSData(bytes: baseData, length: baseData.count)
let baseFullRange = NSRange(location : 0,length : baseData.count)
let noPrefixRange = NSRange(location : 2,length : baseData.count-2)
let noSuffixRange = NSRange(location : 0,length : baseData.count-2)
let notFoundRange = NSRange(location: NSNotFound, length: 0)
let prefixData : [UInt8] = [0x00,0x01]
let prefix = Data(bytes: prefixData, count: prefixData.count)
let prefixRange = NSRange(location: 0, length: prefixData.count)
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.anchored], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: noPrefixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: noPrefixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: noSuffixRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: noSuffixRange),prefixRange))
let suffixData : [UInt8] = [0x03,0x04]
let suffix = Data(bytes: suffixData, count: suffixData.count)
let suffixRange = NSRange(location: 3, length: suffixData.count)
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards,.anchored], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: noPrefixRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: noPrefixRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: noSuffixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: noSuffixRange),notFoundRange))
let sliceData : [UInt8] = [0x02,0x03]
let slice = Data(bytes: sliceData, count: sliceData.count)
let sliceRange = NSRange(location: 2, length: sliceData.count)
XCTAssert(NSEqualRanges(base.range(of: slice, options: [], in: baseFullRange),sliceRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.backwards], in: baseFullRange),sliceRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
let empty = Data()
XCTAssert(NSEqualRanges(base.range(of: empty, options: [], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.backwards], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
}
// Check all of the NSMutableData constructors are available.
func test_initNSMutableData() {
let mData = NSMutableData()
XCTAssertNotNil(mData)
XCTAssertEqual(mData.length, 0)
}
func test_initNSMutableDataWithLength() {
let mData = NSMutableData(length: 30)
XCTAssertNotNil(mData)
XCTAssertEqual(mData!.length, 30)
}
func test_initNSMutableDataWithCapacity() {
let mData = NSMutableData(capacity: 30)
XCTAssertNotNil(mData)
XCTAssertEqual(mData!.length, 0)
}
func test_initNSMutableDataFromData() {
let data = Data(bytes: [1, 2, 3])
let mData = NSMutableData(data: data)
XCTAssertEqual(mData.length, 3)
XCTAssertEqual(NSData(data: data), mData)
}
func test_initNSMutableDataFromBytes() {
let data = Data([1, 2, 3, 4, 5, 6])
var testBytes: [UInt8] = [1, 2, 3, 4, 5, 6]
let md1 = NSMutableData(bytes: &testBytes, length: testBytes.count)
XCTAssertEqual(md1, NSData(data: data))
let md2 = NSMutableData(bytes: nil, length: 0)
XCTAssertEqual(md2.length, 0)
let testBuffer = malloc(testBytes.count)!
let md3 = NSMutableData(bytesNoCopy: testBuffer, length: testBytes.count)
md3.replaceBytes(in: NSRange(location: 0, length: testBytes.count), withBytes: &testBytes)
XCTAssertEqual(md3, NSData(data: data))
let md4 = NSMutableData(bytesNoCopy: &testBytes, length: testBytes.count, deallocator: nil)
XCTAssertEqual(md4.length, testBytes.count)
let md5 = NSMutableData(bytesNoCopy: &testBytes, length: testBytes.count, freeWhenDone: false)
XCTAssertEqual(md5, NSData(data: data))
}
func test_initNSMutableDataContentsOf() {
let testDir = testBundle().resourcePath
let filename = testDir!.appending("/NSStringTestData.txt")
let url = URL(fileURLWithPath: filename)
func testText(_ mData: NSMutableData?) {
guard let mData = mData else {
XCTFail("Contents of file are Nil")
return
}
if let txt = String(data: Data(referencing: mData), encoding: .ascii) {
XCTAssertEqual(txt, "swift-corelibs-foundation")
} else {
XCTFail("Cant convert to string")
}
}
let contents1 = NSMutableData(contentsOfFile: filename)
XCTAssertNotNil(contents1)
testText(contents1)
let contents2 = try? NSMutableData(contentsOfFile: filename, options: [])
XCTAssertNotNil(contents2)
testText(contents2)
let contents3 = NSMutableData(contentsOf: url)
XCTAssertNotNil(contents3)
testText(contents3)
let contents4 = try? NSMutableData(contentsOf: url, options: [])
XCTAssertNotNil(contents4)
testText(contents4)
// Test failure to read
let badFilename = "does not exist"
let badUrl = URL(fileURLWithPath: badFilename)
XCTAssertNil(NSMutableData(contentsOfFile: badFilename))
XCTAssertNil(try? NSMutableData(contentsOfFile: badFilename, options: []))
XCTAssertNil(NSMutableData(contentsOf: badUrl))
XCTAssertNil(try? NSMutableData(contentsOf: badUrl, options: []))
}
func test_initNSMutableDataBase64() {
let srcData = Data([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
let base64Data = srcData.base64EncodedData()
let base64String = srcData.base64EncodedString()
XCTAssertEqual(base64String, "AQIDBAUGBwgJAA==")
let mData1 = NSMutableData(base64Encoded: base64Data)
XCTAssertNotNil(mData1)
XCTAssertEqual(mData1!, NSData(data: srcData))
let mData2 = NSMutableData(base64Encoded: base64String)
XCTAssertNotNil(mData2)
XCTAssertEqual(mData2!, NSData(data: srcData))
// Test bad input
XCTAssertNil(NSMutableData(base64Encoded: Data([1,2,3]), options: []))
XCTAssertNil(NSMutableData(base64Encoded: "x", options: []))
}
func test_replaceBytes() {
var data = Data(bytes: [0, 0, 0, 0, 0])
let newData = Data(bytes: [1, 2, 3, 4, 5])
// test replaceSubrange(_, with:)
XCTAssertFalse(data == newData)
data.replaceSubrange(data.startIndex..<data.endIndex, with: newData)
XCTAssertTrue(data == newData)
// subscript(index:) uses replaceBytes so use it to test edge conditions
data[0] = 0
data[4] = 0
XCTAssertTrue(data == Data(bytes: [0, 2, 3, 4, 0]))
// test NSMutableData.replaceBytes(in:withBytes:length:) directly
func makeData(_ data: [UInt8]) -> NSData {
return NSData(bytes: data, length: data.count)
}
guard let mData = NSMutableData(length: 5) else {
XCTFail("Cant create NSMutableData")
return
}
let replacement = makeData([8, 9, 10])
mData.replaceBytes(in: NSRange(location: 1, length: 3), withBytes: replacement.bytes,
length: 3)
let expected = makeData([0, 8, 9, 10, 0])
XCTAssertEqual(mData, expected)
}
func test_replaceBytesWithNil() {
func makeData(_ data: [UInt8]) -> NSMutableData {
return NSMutableData(bytes: data, length: data.count)
}
let mData = makeData([1, 2, 3, 4, 5])
mData.replaceBytes(in: NSRange(location: 1, length: 3), withBytes: nil, length: 0)
let expected = makeData([1, 5])
XCTAssertEqual(mData, expected)
}
func test_initDataWithCapacity() {
let data = Data(capacity: 123)
XCTAssertEqual(data.count, 0)
}
func test_initDataWithCount() {
let dataSize = 1024
let data = Data(count: dataSize)
XCTAssertEqual(data.count, dataSize)
if let index = (data.index { $0 != 0 }) {
XCTFail("Byte at index: \(index) is not zero: \(data[index])")
return
}
}
func test_emptyStringToData() {
let data = "".data(using: .utf8)!
XCTAssertEqual(0, data.count, "data from empty string is empty")
}
}
// Tests from Swift SDK Overlay
extension TestNSData {
func testBasicConstruction() throws {
// Make sure that we were able to create some data
let hello = dataFrom("hello")
let helloLength = hello.count
XCTAssertEqual(hello[0], 0x68, "Unexpected first byte")
let world = dataFrom(" world")
var helloWorld = hello
world.withUnsafeBytes {
helloWorld.append($0, count: world.count)
}
XCTAssertEqual(hello[0], 0x68, "First byte should not have changed")
XCTAssertEqual(hello.count, helloLength, "Length of first data should not have changed")
XCTAssertEqual(helloWorld.count, hello.count + world.count, "The total length should include both buffers")
}
func testInitializationWithArray() {
let data = Data(bytes: [1, 2, 3])
XCTAssertEqual(3, data.count)
let data2 = Data(bytes: [1, 2, 3].filter { $0 >= 2 })
XCTAssertEqual(2, data2.count)
let data3 = Data(bytes: [1, 2, 3, 4, 5][1..<3])
XCTAssertEqual(2, data3.count)
}
func testMutableData() {
let hello = dataFrom("hello")
let helloLength = hello.count
XCTAssertEqual(hello[0], 0x68, "Unexpected first byte")
// Double the length
var mutatingHello = hello
mutatingHello.count *= 2
XCTAssertEqual(hello.count, helloLength, "The length of the initial data should not have changed")
XCTAssertEqual(mutatingHello.count, helloLength * 2, "The length should have changed")
// Get the underlying data for hello2
mutatingHello.withUnsafeMutableBytes { (bytes : UnsafeMutablePointer<UInt8>) in
XCTAssertEqual(bytes.pointee, 0x68, "First byte should be 0x68")
// Mutate it
bytes.pointee = 0x67
XCTAssertEqual(bytes.pointee, 0x67, "First byte should be 0x67")
}
XCTAssertEqual(mutatingHello[0], 0x67, "First byte accessed via other method should still be 0x67")
// Verify that the first data is still correct
XCTAssertEqual(hello[0], 0x68, "The first byte should still be 0x68")
}
func testBridgingDefault() {
let hello = dataFrom("hello")
// Convert from struct Data to NSData
if let s = NSString(data: hello, encoding: String.Encoding.utf8.rawValue) {
XCTAssertTrue(s.isEqual(to: "hello"), "The strings should be equal")
}
// Convert from NSData to struct Data
let goodbye = dataFrom("goodbye")
if let resultingData = NSString(string: "goodbye").data(using: String.Encoding.utf8.rawValue) {
XCTAssertEqual(resultingData[0], goodbye[0], "First byte should be equal")
}
}
func testBridgingMutable() {
// Create a mutable data
var helloWorld = dataFrom("hello")
helloWorld.append(dataFrom("world"))
// Convert from struct Data to NSData
if let s = NSString(data: helloWorld, encoding: String.Encoding.utf8.rawValue) {
XCTAssertTrue(s.isEqual(to: "helloworld"), "The strings should be equal")
}
}
func testEquality() {
let d1 = dataFrom("hello")
let d2 = dataFrom("hello")
// Use == explicitly here to make sure we're calling the right methods
XCTAssertTrue(d1 == d2, "Data should be equal")
}
func testDataInSet() {
let d1 = dataFrom("Hello")
let d2 = dataFrom("Hello")
let d3 = dataFrom("World")
var s = Set<Data>()
s.insert(d1)
s.insert(d2)
s.insert(d3)
XCTAssertEqual(s.count, 2, "Expected only two entries in the Set")
}
func testReplaceSubrange() {
var hello = dataFrom("Hello")
let world = dataFrom("World")
hello[0] = world[0]
XCTAssertEqual(hello[0], world[0])
var goodbyeWorld = dataFrom("Hello World")
let goodbye = dataFrom("Goodbye")
let expected = dataFrom("Goodbye World")
goodbyeWorld.replaceSubrange(0..<5, with: goodbye)
XCTAssertEqual(goodbyeWorld, expected)
}
func testReplaceSubrange2() {
let hello = dataFrom("Hello")
let world = dataFrom(" World")
let goodbye = dataFrom("Goodbye")
let expected = dataFrom("Goodbye World")
var mutateMe = hello
mutateMe.append(world)
if let found = mutateMe.range(of: hello) {
mutateMe.replaceSubrange(found, with: goodbye)
}
XCTAssertEqual(mutateMe, expected)
}
func testReplaceSubrange3() {
// The expected result
let expectedBytes : [UInt8] = [1, 2, 9, 10, 11, 12, 13]
let expected = expectedBytes.withUnsafeBufferPointer {
return Data(buffer: $0)
}
// The data we'll mutate
let someBytes : [UInt8] = [1, 2, 3, 4, 5]
var a = someBytes.withUnsafeBufferPointer {
return Data(buffer: $0)
}
// The bytes we'll insert
let b : [UInt8] = [9, 10, 11, 12, 13]
b.withUnsafeBufferPointer {
a.replaceSubrange(2..<5, with: $0)
}
XCTAssertEqual(expected, a)
}
func testReplaceSubrange4() {
let expectedBytes : [UInt8] = [1, 2, 9, 10, 11, 12, 13]
let expected = Data(bytes: expectedBytes)
// The data we'll mutate
let someBytes : [UInt8] = [1, 2, 3, 4, 5]
var a = Data(bytes: someBytes)
// The bytes we'll insert
let b : [UInt8] = [9, 10, 11, 12, 13]
a.replaceSubrange(2..<5, with: b)
XCTAssertEqual(expected, a)
}
func testReplaceSubrange5() {
var d = Data(bytes: [1, 2, 3])
d.replaceSubrange(0..<0, with: [4])
XCTAssertEqual(Data(bytes: [4, 1, 2, 3]), d)
d.replaceSubrange(0..<4, with: [9])
XCTAssertEqual(Data(bytes: [9]), d)
d.replaceSubrange(0..<d.count, with: [])
XCTAssertEqual(Data(), d)
d.replaceSubrange(0..<0, with: [1, 2, 3, 4])
XCTAssertEqual(Data(bytes: [1, 2, 3, 4]), d)
d.replaceSubrange(1..<3, with: [9, 8])
XCTAssertEqual(Data(bytes: [1, 9, 8, 4]), d)
d.replaceSubrange(d.count..<d.count, with: [5])
XCTAssertEqual(Data(bytes: [1, 9, 8, 4, 5]), d)
}
func testRange() {
let helloWorld = dataFrom("Hello World")
let goodbye = dataFrom("Goodbye")
let hello = dataFrom("Hello")
do {
let found = helloWorld.range(of: goodbye)
XCTAssertTrue(found == nil || found!.isEmpty)
}
do {
let found = helloWorld.range(of: goodbye, options: .anchored)
XCTAssertTrue(found == nil || found!.isEmpty)
}
do {
let found = helloWorld.range(of: hello, in: 7..<helloWorld.count)
XCTAssertTrue(found == nil || found!.isEmpty)
}
}
func testInsertData() {
let hello = dataFrom("Hello")
let world = dataFrom(" World")
let expected = dataFrom("Hello World")
var helloWorld = dataFrom("")
helloWorld.replaceSubrange(0..<0, with: world)
helloWorld.replaceSubrange(0..<0, with: hello)
XCTAssertEqual(helloWorld, expected)
}
func testLoops() {
let hello = dataFrom("Hello")
var count = 0
for _ in hello {
count += 1
}
XCTAssertEqual(count, 5)
}
func testGenericAlgorithms() {
let hello = dataFrom("Hello World")
let isCapital = { (byte : UInt8) in byte >= 65 && byte <= 90 }
let allCaps = hello.filter(isCapital)
XCTAssertEqual(allCaps.count, 2)
let capCount = hello.reduce(0) { isCapital($1) ? $0 + 1 : $0 }
XCTAssertEqual(capCount, 2)
let allLower = hello.map { isCapital($0) ? $0 + 31 : $0 }
XCTAssertEqual(allLower.count, hello.count)
}
func testCustomDeallocator() {
var deallocatorCalled = false
// Scope the data to a block to control lifecycle
do {
let buffer = malloc(16)!
let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: 16)
var data = Data(bytesNoCopy: bytePtr, count: 16, deallocator: .custom({ (ptr, size) in
deallocatorCalled = true
free(UnsafeMutableRawPointer(ptr))
}))
// Use the data
data[0] = 1
}
XCTAssertTrue(deallocatorCalled, "Custom deallocator was never called")
}
func testCopyBytes() {
let c = 10
let underlyingBuffer = malloc(c * MemoryLayout<UInt16>.stride)!
let u16Ptr = underlyingBuffer.bindMemory(to: UInt16.self, capacity: c)
let buffer = UnsafeMutableBufferPointer<UInt16>(start: u16Ptr, count: c)
buffer[0] = 0
buffer[1] = 0
var data = Data(capacity: c * MemoryLayout<UInt16>.stride)
data.resetBytes(in: 0..<c * MemoryLayout<UInt16>.stride)
data[0] = 0xFF
data[1] = 0xFF
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(copiedCount, c * MemoryLayout<UInt16>.stride)
XCTAssertEqual(buffer[0], 0xFFFF)
free(underlyingBuffer)
}
func testCopyBytes_undersized() {
let a : [UInt8] = [1, 2, 3, 4, 5]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let expectedSize = MemoryLayout<UInt8>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize - 1
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
// We should only copy in enough bytes that can fit in the buffer
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(expectedSize - 1, copiedCount)
var index = 0
for v in a[0..<expectedSize-1] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
func testCopyBytes_oversized() {
let a : [Int32] = [1, 0, 1, 0, 1]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let expectedSize = MemoryLayout<Int32>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize + 1
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(expectedSize, copiedCount)
free(underlyingBuffer)
}
func testCopyBytes_ranges() {
do {
// Equal sized buffer, data
let a : [UInt8] = [1, 2, 3, 4, 5]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = data.count
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<0)
XCTAssertEqual(0, copiedCount)
copiedCount = data.copyBytes(to: buffer, from: 1..<1)
XCTAssertEqual(0, copiedCount)
copiedCount = data.copyBytes(to: buffer, from: 0..<3)
XCTAssertEqual((0..<3).count, copiedCount)
var index = 0
for v in a[0..<3] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
do {
// Larger buffer than data
let a : [UInt8] = [1, 2, 3, 4]
let data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = 10
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<3)
XCTAssertEqual((0..<3).count, copiedCount)
var index = 0
for v in a[0..<3] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
do {
// Larger data than buffer
let a : [UInt8] = [1, 2, 3, 4, 5, 6]
let data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = 4
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<data.index(before: data.endIndex))
XCTAssertEqual(4, copiedCount)
var index = 0
for v in a[0..<4] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
}
func test_base64Data_small() {
let data = "Hello World".data(using: .utf8)!
let base64 = data.base64EncodedString()
XCTAssertEqual("SGVsbG8gV29ybGQ=", base64, "trivial base64 conversion should work")
}
func test_dataHash() {
let dataStruct = "Hello World".data(using: .utf8)!
let dataObj = dataStruct._bridgeToObjectiveC()
XCTAssertEqual(dataObj.hashValue, dataStruct.hashValue, "Data and NSData should have the same hash value")
}
func test_base64Data_medium() {
let data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut at tincidunt arcu. Suspendisse nec sodales erat, sit amet imperdiet ipsum. Etiam sed ornare felis. Nunc mauris turpis, bibendum non lectus quis, malesuada placerat turpis. Nam adipiscing non massa et semper. Nulla convallis semper bibendum. Aliquam dictum nulla cursus mi ultricies, at tincidunt mi sagittis. Nulla faucibus at dui quis sodales. Morbi rutrum, dui id ultrices venenatis, arcu urna egestas felis, vel suscipit mauris arcu quis risus. Nunc venenatis ligula at orci tristique, et mattis purus pulvinar. Etiam ultricies est odio. Nunc eleifend malesuada justo, nec euismod sem ultrices quis. Etiam nec nibh sit amet lorem faucibus dapibus quis nec leo. Praesent sit amet mauris vel lacus hendrerit porta mollis consectetur mi. Donec eget tortor dui. Morbi imperdiet, arcu sit amet elementum interdum, quam nisl tempor quam, vitae feugiat augue purus sed lacus. In ac urna adipiscing purus venenatis volutpat vel et metus. Nullam nec auctor quam. Phasellus porttitor felis ac nibh gravida suscipit tempus at ante. Nunc pellentesque iaculis sapien a mattis. Aenean eleifend dolor non nunc laoreet, non dictum massa aliquam. Aenean quis turpis augue. Praesent augue lectus, mollis nec elementum eu, dignissim at velit. Ut congue neque id ullamcorper pellentesque. Maecenas euismod in elit eu vehicula. Nullam tristique dui nulla, nec convallis metus suscipit eget. Cras semper augue nec cursus blandit. Nulla rhoncus et odio quis blandit. Praesent lobortis dignissim velit ut pulvinar. Duis interdum quam adipiscing dolor semper semper. Nunc bibendum convallis dui, eget mollis magna hendrerit et. Morbi facilisis, augue eu fringilla convallis, mauris est cursus dolor, eu posuere odio nunc quis orci. Ut eu justo sem. Phasellus ut erat rhoncus, faucibus arcu vitae, vulputate erat. Aliquam nec magna viverra, interdum est vitae, rhoncus sapien. Duis tincidunt tempor ipsum ut dapibus. Nullam commodo varius metus, sed sollicitudin eros. Etiam nec odio et dui tempor blandit posuere.".data(using: .utf8)!
let base64 = data.base64EncodedString()
XCTAssertEqual("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgYXQgdGluY2lkdW50IGFyY3UuIFN1c3BlbmRpc3NlIG5lYyBzb2RhbGVzIGVyYXQsIHNpdCBhbWV0IGltcGVyZGlldCBpcHN1bS4gRXRpYW0gc2VkIG9ybmFyZSBmZWxpcy4gTnVuYyBtYXVyaXMgdHVycGlzLCBiaWJlbmR1bSBub24gbGVjdHVzIHF1aXMsIG1hbGVzdWFkYSBwbGFjZXJhdCB0dXJwaXMuIE5hbSBhZGlwaXNjaW5nIG5vbiBtYXNzYSBldCBzZW1wZXIuIE51bGxhIGNvbnZhbGxpcyBzZW1wZXIgYmliZW5kdW0uIEFsaXF1YW0gZGljdHVtIG51bGxhIGN1cnN1cyBtaSB1bHRyaWNpZXMsIGF0IHRpbmNpZHVudCBtaSBzYWdpdHRpcy4gTnVsbGEgZmF1Y2lidXMgYXQgZHVpIHF1aXMgc29kYWxlcy4gTW9yYmkgcnV0cnVtLCBkdWkgaWQgdWx0cmljZXMgdmVuZW5hdGlzLCBhcmN1IHVybmEgZWdlc3RhcyBmZWxpcywgdmVsIHN1c2NpcGl0IG1hdXJpcyBhcmN1IHF1aXMgcmlzdXMuIE51bmMgdmVuZW5hdGlzIGxpZ3VsYSBhdCBvcmNpIHRyaXN0aXF1ZSwgZXQgbWF0dGlzIHB1cnVzIHB1bHZpbmFyLiBFdGlhbSB1bHRyaWNpZXMgZXN0IG9kaW8uIE51bmMgZWxlaWZlbmQgbWFsZXN1YWRhIGp1c3RvLCBuZWMgZXVpc21vZCBzZW0gdWx0cmljZXMgcXVpcy4gRXRpYW0gbmVjIG5pYmggc2l0IGFtZXQgbG9yZW0gZmF1Y2lidXMgZGFwaWJ1cyBxdWlzIG5lYyBsZW8uIFByYWVzZW50IHNpdCBhbWV0IG1hdXJpcyB2ZWwgbGFjdXMgaGVuZHJlcml0IHBvcnRhIG1vbGxpcyBjb25zZWN0ZXR1ciBtaS4gRG9uZWMgZWdldCB0b3J0b3IgZHVpLiBNb3JiaSBpbXBlcmRpZXQsIGFyY3Ugc2l0IGFtZXQgZWxlbWVudHVtIGludGVyZHVtLCBxdWFtIG5pc2wgdGVtcG9yIHF1YW0sIHZpdGFlIGZldWdpYXQgYXVndWUgcHVydXMgc2VkIGxhY3VzLiBJbiBhYyB1cm5hIGFkaXBpc2NpbmcgcHVydXMgdmVuZW5hdGlzIHZvbHV0cGF0IHZlbCBldCBtZXR1cy4gTnVsbGFtIG5lYyBhdWN0b3IgcXVhbS4gUGhhc2VsbHVzIHBvcnR0aXRvciBmZWxpcyBhYyBuaWJoIGdyYXZpZGEgc3VzY2lwaXQgdGVtcHVzIGF0IGFudGUuIE51bmMgcGVsbGVudGVzcXVlIGlhY3VsaXMgc2FwaWVuIGEgbWF0dGlzLiBBZW5lYW4gZWxlaWZlbmQgZG9sb3Igbm9uIG51bmMgbGFvcmVldCwgbm9uIGRpY3R1bSBtYXNzYSBhbGlxdWFtLiBBZW5lYW4gcXVpcyB0dXJwaXMgYXVndWUuIFByYWVzZW50IGF1Z3VlIGxlY3R1cywgbW9sbGlzIG5lYyBlbGVtZW50dW0gZXUsIGRpZ25pc3NpbSBhdCB2ZWxpdC4gVXQgY29uZ3VlIG5lcXVlIGlkIHVsbGFtY29ycGVyIHBlbGxlbnRlc3F1ZS4gTWFlY2VuYXMgZXVpc21vZCBpbiBlbGl0IGV1IHZlaGljdWxhLiBOdWxsYW0gdHJpc3RpcXVlIGR1aSBudWxsYSwgbmVjIGNvbnZhbGxpcyBtZXR1cyBzdXNjaXBpdCBlZ2V0LiBDcmFzIHNlbXBlciBhdWd1ZSBuZWMgY3Vyc3VzIGJsYW5kaXQuIE51bGxhIHJob25jdXMgZXQgb2RpbyBxdWlzIGJsYW5kaXQuIFByYWVzZW50IGxvYm9ydGlzIGRpZ25pc3NpbSB2ZWxpdCB1dCBwdWx2aW5hci4gRHVpcyBpbnRlcmR1bSBxdWFtIGFkaXBpc2NpbmcgZG9sb3Igc2VtcGVyIHNlbXBlci4gTnVuYyBiaWJlbmR1bSBjb252YWxsaXMgZHVpLCBlZ2V0IG1vbGxpcyBtYWduYSBoZW5kcmVyaXQgZXQuIE1vcmJpIGZhY2lsaXNpcywgYXVndWUgZXUgZnJpbmdpbGxhIGNvbnZhbGxpcywgbWF1cmlzIGVzdCBjdXJzdXMgZG9sb3IsIGV1IHBvc3VlcmUgb2RpbyBudW5jIHF1aXMgb3JjaS4gVXQgZXUganVzdG8gc2VtLiBQaGFzZWxsdXMgdXQgZXJhdCByaG9uY3VzLCBmYXVjaWJ1cyBhcmN1IHZpdGFlLCB2dWxwdXRhdGUgZXJhdC4gQWxpcXVhbSBuZWMgbWFnbmEgdml2ZXJyYSwgaW50ZXJkdW0gZXN0IHZpdGFlLCByaG9uY3VzIHNhcGllbi4gRHVpcyB0aW5jaWR1bnQgdGVtcG9yIGlwc3VtIHV0IGRhcGlidXMuIE51bGxhbSBjb21tb2RvIHZhcml1cyBtZXR1cywgc2VkIHNvbGxpY2l0dWRpbiBlcm9zLiBFdGlhbSBuZWMgb2RpbyBldCBkdWkgdGVtcG9yIGJsYW5kaXQgcG9zdWVyZS4=", base64, "medium base64 conversion should work")
}
func test_openingNonExistentFile() {
var didCatchError = false
do {
let _ = try NSData(contentsOfFile: "does not exist", options: [])
} catch {
didCatchError = true
}
XCTAssertTrue(didCatchError)
}
func test_contentsOfFile() {
let testDir = testBundle().resourcePath
let filename = testDir!.appending("/NSStringTestData.txt")
let contents = NSData(contentsOfFile: filename)
XCTAssertNotNil(contents)
if let contents = contents {
let ptr = UnsafeMutableRawPointer(mutating: contents.bytes)
let str = String(bytesNoCopy: ptr, length: contents.length,
encoding: .ascii, freeWhenDone: false)
XCTAssertEqual(str, "swift-corelibs-foundation")
}
}
func test_contentsOfZeroFile() {
#if os(Linux)
guard FileManager.default.fileExists(atPath: "/proc/self") else {
return
}
let contents = NSData(contentsOfFile: "/proc/self/cmdline")
XCTAssertNotNil(contents)
if let contents = contents {
XCTAssertTrue(contents.length > 0)
let ptr = UnsafeMutableRawPointer(mutating: contents.bytes)
let str = String(bytesNoCopy: ptr, length: contents.length,
encoding: .ascii, freeWhenDone: false)
XCTAssertNotNil(str)
if let str = str {
XCTAssertTrue(str.hasSuffix("TestFoundation"))
}
}
do {
let maps = try String(contentsOfFile: "/proc/self/maps", encoding: .utf8)
XCTAssertTrue(maps.count > 0)
} catch {
XCTFail("Cannot read /proc/self/maps: \(String(describing: error))")
}
#endif
}
func test_basicReadWrite() {
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testfile")
let count = 1 << 24
let randomMemory = malloc(count)!
let ptr = randomMemory.bindMemory(to: UInt8.self, capacity: count)
let data = Data(bytesNoCopy: ptr, count: count, deallocator: .free)
do {
try data.write(to: url)
let readData = try Data(contentsOf: url)
XCTAssertEqual(data, readData)
} catch {
XCTFail("Should not have thrown")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
}
func test_writeFailure() {
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testfile")
let data = Data()
do {
try data.write(to: url)
} catch let error as NSError {
print(error)
XCTAssertTrue(false, "Should not have thrown")
} catch {
XCTFail("unexpected error")
}
do {
try data.write(to: url, options: [.withoutOverwriting])
XCTAssertTrue(false, "Should have thrown")
} catch let error as NSError {
XCTAssertEqual(error.code, CocoaError.fileWriteFileExists.rawValue)
} catch {
XCTFail("unexpected error")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
// Make sure clearing the error condition allows the write to succeed
do {
try data.write(to: url, options: [.withoutOverwriting])
} catch {
XCTAssertTrue(false, "Should not have thrown")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
}
func test_genericBuffers() {
let a : [Int32] = [1, 0, 1, 0, 1]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
var expectedSize = MemoryLayout<Int32>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
[false, true].withUnsafeBufferPointer {
data.append($0)
}
expectedSize += MemoryLayout<Bool>.stride * 2
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(copiedCount, expectedSize)
free(underlyingBuffer)
}
// intentionally structured so sizeof() != strideof()
struct MyStruct {
var time: UInt64
let x: UInt32
let y: UInt32
let z: UInt32
init() {
time = 0
x = 1
y = 2
z = 3
}
}
func test_bufferSizeCalculation() {
// Make sure that Data is correctly using strideof instead of sizeof.
// n.b. if sizeof(MyStruct) == strideof(MyStruct), this test is not as useful as it could be
// init
let stuff = [MyStruct(), MyStruct(), MyStruct()]
var data = stuff.withUnsafeBufferPointer {
return Data(buffer: $0)
}
XCTAssertEqual(data.count, MemoryLayout<MyStruct>.stride * 3)
// append
stuff.withUnsafeBufferPointer {
data.append($0)
}
XCTAssertEqual(data.count, MemoryLayout<MyStruct>.stride * 6)
// copyBytes
do {
// equal size
let underlyingBuffer = malloc(6 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 6)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(6 * MemoryLayout<MyStruct>.stride, byteCount)
}
do {
// undersized
let underlyingBuffer = malloc(3 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 3)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 3)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(3 * MemoryLayout<MyStruct>.stride, byteCount)
}
do {
// oversized
let underlyingBuffer = malloc(12 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 6)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(6 * MemoryLayout<MyStruct>.stride, byteCount)
}
}
func test_repeatingValueInitialization() {
var d = Data(repeating: 0x01, count: 3)
let elements = repeatElement(UInt8(0x02), count: 3) // ensure we fall into the sequence case
d.append(contentsOf: elements)
XCTAssertEqual(d[0], 0x01)
XCTAssertEqual(d[1], 0x01)
XCTAssertEqual(d[2], 0x01)
XCTAssertEqual(d[3], 0x02)
XCTAssertEqual(d[4], 0x02)
XCTAssertEqual(d[5], 0x02)
}
func test_sliceAppending() {
// https://bugs.swift.org/browse/SR-4473
var fooData = Data()
let barData = Data([0, 1, 2, 3, 4, 5])
let slice = barData.suffix(from: 3)
fooData.append(slice)
XCTAssertEqual(fooData[0], 0x03)
XCTAssertEqual(fooData[1], 0x04)
XCTAssertEqual(fooData[2], 0x05)
}
func test_replaceSubrange() {
// https://bugs.swift.org/browse/SR-4462
let data = Data(bytes: [0x01, 0x02])
var dataII = Data(base64Encoded: data.base64EncodedString())!
dataII.replaceSubrange(0..<1, with: Data())
XCTAssertEqual(dataII[0], 0x02)
}
func test_sliceWithUnsafeBytes() {
let base = Data([0, 1, 2, 3, 4, 5])
let slice = base[2..<4]
let segment = slice.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> [UInt8] in
return [ptr.pointee, ptr.advanced(by: 1).pointee]
}
XCTAssertEqual(segment, [UInt8(2), UInt8(3)])
}
func test_sliceIteration() {
let base = Data([0, 1, 2, 3, 4, 5])
let slice = base[2..<4]
var found = [UInt8]()
for byte in slice {
found.append(byte)
}
XCTAssertEqual(found[0], 2)
XCTAssertEqual(found[1], 3)
}
func test_validateMutation_withUnsafeMutableBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 0xFF, 6, 7, 8, 9]))
}
func test_validateMutation_appendBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0x5)
}
func test_validateMutation_appendData() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let other = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append(other)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
func test_validateMutation_appendBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
func test_validateMutation_appendSequence() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let seq = repeatElement(UInt8(1), count: 10)
data.append(contentsOf: seq)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 1)
}
func test_validateMutation_appendContentsOf() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data.append(contentsOf: bytes)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
func test_validateMutation_resetBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 0, 0, 0, 8, 9]))
}
func test_validateMutation_replaceSubrange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
func test_validateMutation_replaceSubrangeCountableRange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
func test_validateMutation_replaceSubrangeWithBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
func test_validateMutation_replaceSubrangeWithCollection() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
func test_validateMutation_replaceSubrangeWithBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
func test_validateMutation_slice_withUnsafeMutableBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 6, 7, 8]))
}
func test_validateMutation_slice_appendBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_appendData() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let other = Data(bytes: [0xFF, 0xFF])
data.append(other)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_appendBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_appendSequence() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let seq = repeatElement(UInt8(0xFF), count: 2)
data.append(contentsOf: seq)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_appendContentsOf() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_resetBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
func test_validateMutation_slice_replaceSubrange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_replaceSubrangeCountableRange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_replaceSubrangeWithBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_replaceSubrangeWithCollection() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_replaceSubrangeWithBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_cow_withUnsafeMutableBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 0xFF, 6, 7, 8, 9]))
}
}
func test_validateMutation_cow_appendBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 0x9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x68)
}
}
func test_validateMutation_cow_appendData() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let other = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append(other)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
}
func test_validateMutation_cow_appendBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
}
func test_validateMutation_cow_appendSequence() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let seq = repeatElement(UInt8(1), count: 10)
data.append(contentsOf: seq)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 1)
}
}
func test_validateMutation_cow_appendContentsOf() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data.append(contentsOf: bytes)
XCTAssertEqual(data[data.startIndex.advanced(by: 9)], 9)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0)
}
}
func test_validateMutation_cow_resetBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 0, 0, 0, 8, 9]))
}
}
func test_validateMutation_cow_replaceSubrange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
}
func test_validateMutation_cow_replaceSubrangeCountableRange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
}
func test_validateMutation_cow_replaceSubrangeWithBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
}
func test_validateMutation_cow_replaceSubrangeWithCollection() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
}
func test_validateMutation_cow_replaceSubrangeWithBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 0xFF, 0xFF, 9]))
}
}
func test_validateMutation_slice_cow_withUnsafeMutableBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 6, 7, 8]))
}
}
func test_validateMutation_slice_cow_appendBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 4)], 0x8)
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0x68)
}
}
func test_validateMutation_slice_cow_appendData() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let other = Data(bytes: [0xFF, 0xFF])
data.append(other)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_appendBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_appendSequence() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let seq = repeatElement(UInt8(0xFF), count: 2)
data.append(contentsOf: seq)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_appendContentsOf() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_resetBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
}
func test_validateMutation_slice_cow_replaceSubrange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_replaceSubrangeCountableRange() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_replaceSubrangeWithBuffer() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_replaceSubrangeWithCollection() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_replaceSubrangeWithBytes() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_immutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
func test_validateMutation_immutableBacking_appendBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0x68)
}
func test_validateMutation_immutableBacking_appendData() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let other = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append(other)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0)
}
func test_validateMutation_immutableBacking_appendBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0)
}
func test_validateMutation_immutableBacking_appendSequence() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let seq = repeatElement(UInt8(1), count: 10)
data.append(contentsOf: seq)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 1)
}
func test_validateMutation_immutableBacking_appendContentsOf() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data.append(contentsOf: bytes)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0)
}
func test_validateMutation_immutableBacking_resetBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x72, 0x6c, 0x64]))
}
func test_validateMutation_immutableBacking_replaceSubrange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xFF, 0xFF, 0x6c, 0x64]))
}
func test_validateMutation_immutableBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xFF, 0xFF, 0x6c, 0x64]))
}
func test_validateMutation_immutableBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xFF, 0xFF, 0x6c, 0x64]))
}
func test_validateMutation_immutableBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xFF, 0xFF, 0x6c, 0x64]))
}
func test_validateMutation_immutableBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xFF, 0xFF, 0x6c, 0x64]))
}
func test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))[4..<9]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_immutableBacking_appendBytes() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_appendData() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_appendBuffer() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_appendSequence() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_appendContentsOf() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_resetBytes() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
func test_validateMutation_slice_immutableBacking_replaceSubrange() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_immutableBacking_replaceSubrangeCountableRange() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_immutableBacking_replaceSubrangeWithBuffer() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_immutableBacking_replaceSubrangeWithCollection() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with:replacement)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_slice_immutableBacking_replaceSubrangeWithBytes() {
let base: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = base.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
func test_validateMutation_cow_immutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
}
func test_validateMutation_cow_immutableBacking_appendBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0x68)
}
}
func test_validateMutation_cow_immutableBacking_appendData() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let other = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append(other)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0)
}
}
func test_validateMutation_cow_immutableBacking_appendBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 0)
}
}
func test_validateMutation_cow_immutableBacking_appendSequence() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let seq = repeatElement(UInt8(1), count: 10)
data.append(contentsOf: seq)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 1)
}
}
func test_validateMutation_cow_immutableBacking_appendContentsOf() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let bytes: [UInt8] = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data.append(contentsOf: bytes)
XCTAssertEqual(data[data.startIndex.advanced(by: 10)], 0x64)
XCTAssertEqual(data[data.startIndex.advanced(by: 11)], 1)
}
}
func test_validateMutation_cow_immutableBacking_resetBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x72, 0x6c, 0x64]))
}
}
func test_validateMutation_cow_immutableBacking_replaceSubrange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64]))
}
}
func test_validateMutation_cow_immutableBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64]))
}
}
func test_validateMutation_cow_immutableBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [0x68, 0xff, 0xff, 0x64]))
}
}
func test_validateMutation_cow_immutableBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0xff, 0xff, 0x64]))
}
}
func test_validateMutation_cow_immutableBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
holdReference(data) {
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [0x68, 0xff, 0xff, 0x64]))
}
}
func test_validateMutation_slice_cow_immutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))[4..<9]
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
}
func test_validateMutation_slice_cow_immutableBacking_appendBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_immutableBacking_appendData() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_immutableBacking_appendBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer{ data.append($0) }
XCTAssertEqual(data, Data(bytes: [0x6f, 0x20, 0x77, 0x6f, 0x72, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_immutableBacking_appendSequence() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let bytes = repeatElement(UInt8(0xFF), count: 2)
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_immutableBacking_appendContentsOf() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_immutableBacking_resetBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
}
func test_validateMutation_slice_cow_immutableBacking_replaceSubrange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_immutableBacking_replaceSubrangeCountableRange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBuffer() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithCollection() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_immutableBacking_replaceSubrangeWithBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))[4..<9]
}
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes { data.replaceSubrange(range, with: $0.baseAddress!, count: 2) }
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_mutableBacking_withUnsafeMutableBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
func test_validateMutation_mutableBacking_appendBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xFF, 0xFF]))
}
func test_validateMutation_mutableBacking_appendData() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xFF, 0xFF]))
}
func test_validateMutation_mutableBacking_appendBuffer() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xFF, 0xFF]))
}
func test_validateMutation_mutableBacking_appendSequence() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xFF, 0xFF]))
}
func test_validateMutation_mutableBacking_appendContentsOf() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xFF, 0xFF]))
}
func test_validateMutation_mutableBacking_resetBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0, 1, 2, 3, 4, 0, 0, 0, 8, 9]))
}
func test_validateMutation_mutableBacking_replaceSubrange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 9]))
}
func test_validateMutation_mutableBacking_replaceSubrangeCountableRange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 9]))
}
func test_validateMutation_mutableBacking_replaceSubrangeWithBuffer() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer {
data.replaceSubrange(range, with: $0)
}
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 9]))
}
func test_validateMutation_mutableBacking_replaceSubrangeWithCollection() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 9]))
}
func test_validateMutation_mutableBacking_replaceSubrangeWithBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var data = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
data.append(contentsOf: [7, 8, 9])
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count)
}
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 9]))
}
func test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_mutableBacking_appendBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_mutableBacking_appendData() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
func test_validateMutation_slice_mutableBacking_appendBuffer() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let bytes: [UInt8] = [1, 2, 3]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [0x6f, 0x20, 0x77, 0x6f, 0x72, 0x1, 0x2, 0x3]))
}
func test_validateMutation_slice_mutableBacking_appendSequence() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let seq = repeatElement(UInt8(1), count: 3)
data.append(contentsOf: seq)
XCTAssertEqual(data, Data(bytes: [0x6f, 0x20, 0x77, 0x6f, 0x72, 0x1, 0x1, 0x1]))
}
func test_validateMutation_slice_mutableBacking_appendContentsOf() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let bytes: [UInt8] = [1, 2, 3]
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [0x6f, 0x20, 0x77, 0x6f, 0x72, 0x1, 0x2, 0x3]))
}
func test_validateMutation_slice_mutableBacking_resetBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
func test_validateMutation_slice_mutableBacking_replaceSubrange() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0x6f, 0xFF, 0xFF, 0x72]))
}
func test_validateMutation_slice_mutableBacking_replaceSubrangeCountableRange() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0x6f, 0xFF, 0xFF, 0x72]))
}
func test_validateMutation_slice_mutableBacking_replaceSubrangeWithBuffer() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [0x6f, 0xFF, 0xFF, 0x72]))
}
func test_validateMutation_slice_mutableBacking_replaceSubrangeWithCollection() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let replacement: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with:replacement)
XCTAssertEqual(data, Data(bytes: [0x6f, 0xFF, 0xFF, 0x72]))
}
func test_validateMutation_slice_mutableBacking_replaceSubrangeWithBytes() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
replacement.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [0x6f, 0xFF, 0xFF, 0x72]))
}
func test_validateMutation_cow_mutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
}
func test_validateMutation_cow_mutableBacking_appendBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 16)], 6)
XCTAssertEqual(data[data.startIndex.advanced(by: 17)], 0x68)
}
}
func test_validateMutation_cow_mutableBacking_appendData() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
data.append("hello", count: 5)
XCTAssertEqual(data[data.startIndex.advanced(by: 16)], 6)
XCTAssertEqual(data[data.startIndex.advanced(by: 17)], 0x68)
}
}
func test_validateMutation_cow_mutableBacking_appendBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let other = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
data.append(other)
XCTAssertEqual(data[data.startIndex.advanced(by: 16)], 6)
XCTAssertEqual(data[data.startIndex.advanced(by: 17)], 0)
}
}
func test_validateMutation_cow_mutableBacking_appendSequence() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let seq = repeatElement(UInt8(1), count: 10)
data.append(contentsOf: seq)
XCTAssertEqual(data[data.startIndex.advanced(by: 16)], 6)
XCTAssertEqual(data[data.startIndex.advanced(by: 17)], 1)
}
}
func test_validateMutation_cow_mutableBacking_appendContentsOf() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let bytes: [UInt8] = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data.append(contentsOf: bytes)
XCTAssertEqual(data[data.startIndex.advanced(by: 16)], 6)
XCTAssertEqual(data[data.startIndex.advanced(by: 17)], 1)
}
}
func test_validateMutation_cow_mutableBacking_resetBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x72, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_cow_mutableBacking_replaceSubrange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_cow_mutableBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement = Data(bytes: [0xFF, 0xFF])
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_cow_mutableBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
let replacement: [UInt8] = [0xFF, 0xFF]
replacement.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_cow_mutableBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
data.replaceSubrange(range, with: replacement)
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_cow_mutableBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))
data.append(contentsOf: [1, 2, 3, 4, 5, 6])
holdReference(data) {
let replacement: [UInt8] = [0xFF, 0xFF]
let range: Range<Data.Index> = data.startIndex.advanced(by: 4)..<data.startIndex.advanced(by: 9)
replacement.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [0x68, 0x65, 0x6c, 0x6c, 0xff, 0xff, 0x6c, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]))
}
}
func test_validateMutation_slice_cow_mutableBacking_withUnsafeMutableBytes() {
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<9]
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
}
func test_validateMutation_slice_cow_mutableBacking_appendBytes() {
let bytes: [UInt8] = [0, 1, 2]
var base = bytes.withUnsafeBytes { (ptr) in
return Data(referencing: NSData(bytes: ptr.baseAddress!, length: ptr.count))
}
base.append(contentsOf: [3, 4, 5])
var data = base[1..<4]
holdReference(data) {
let bytesToAppend: [UInt8] = [6, 7, 8]
bytesToAppend.withUnsafeBytes { (ptr) in
data.append(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), count: ptr.count)
}
XCTAssertEqual(data, Data(bytes: [1, 2, 3, 6, 7, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_appendData() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_mutableBacking_appendBuffer() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer{ data.append($0) }
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_mutableBacking_appendSequence() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let bytes = repeatElement(UInt8(0xFF), count: 2)
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_mutableBacking_appendContentsOf() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
data.append(contentsOf: bytes)
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 8, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_mutableBacking_resetBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [4, 0, 0, 0, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_replaceSubrange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_replaceSubrangeCountableRange() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let range: CountableRange<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBuffer() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithCollection() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
data.replaceSubrange(range, with: bytes)
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_slice_cow_mutableBacking_replaceSubrangeWithBytes() {
let baseBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6]
var base = baseBytes.withUnsafeBufferPointer {
return Data(referencing: NSData(bytes: $0.baseAddress!, length: $0.count))
}
base.append(contentsOf: [7, 8, 9])
var data = base[4..<9]
holdReference(data) {
let range: Range<Data.Index> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes { data.replaceSubrange(range, with: $0.baseAddress!, count: 2) }
XCTAssertEqual(data, Data(bytes: [4, 0xFF, 0xFF, 8]))
}
}
func test_validateMutation_customBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 1, 1, 1, 1]))
}
#if false // this requires factory patterns
func test_validateMutation_customBacking_appendBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_customBacking_appendData() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_customBacking_appendBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { (buffer) in
data.append(buffer)
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_customBacking_appendSequence() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_customBacking_appendContentsOf() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_customBacking_resetBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0, 0, 0, 1, 1]))
}
func test_validateMutation_customBacking_replaceSubrange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let range: Range<Int> = 1..<4
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1, 1, 1, 1, 1, 1]))
}
func test_validateMutation_customBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let range: CountableRange<Int> = 1..<4
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1, 1, 1, 1, 1, 1]))
}
func test_validateMutation_customBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let bytes: [UInt8] = [0xFF, 0xFF]
let range: Range<Int> = 1..<4
bytes.withUnsafeBufferPointer { (buffer) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1, 1, 1, 1, 1, 1]))
}
func test_validateMutation_customBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let range: Range<Int> = 1..<4
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1, 1, 1, 1, 1, 1]))
}
func test_validateMutation_customBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
let bytes: [UInt8] = [0xFF, 0xFF]
let range: Range<Int> = 1..<5
bytes.withUnsafeBufferPointer { (buffer) in
data.replaceSubrange(range, with: buffer.baseAddress!, count: buffer.count)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1, 1, 1, 1, 1]))
}
func test_validateMutation_slice_customBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_customBacking_appendBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes { ptr in
data.append(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), count: ptr.count)
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customBacking_appendData() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customBacking_appendBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { (buffer) in
data.append(buffer)
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customBacking_appendSequence() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let seq = repeatElement(UInt8(0xFF), count: 2)
data.append(contentsOf: seq)
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customBacking_appendContentsOf() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customBacking_resetBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 1]))
}
func test_validateMutation_slice_customBacking_replaceSubrange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
func test_validateMutation_slice_customBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
func test_validateMutation_slice_customBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { (buffer) in
data.replaceSubrange(range, with: buffer)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
func test_validateMutation_slice_customBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
func test_validateMutation_slice_customBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes { buffer in
data.replaceSubrange(range, with: buffer.baseAddress!, count: 2)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
func test_validateMutation_cow_customBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
}
func test_validateMutation_cow_customBacking_appendBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { (buffer) in
data.append(buffer.baseAddress!, count: buffer.count)
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customBacking_appendData() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customBacking_appendBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customBacking_appendSequence() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customBacking_appendContentsOf() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customBacking_resetBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0, 0, 0, 1, 1]))
}
}
func test_validateMutation_cow_customBacking_replaceSubrange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_cow_customBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_cow_customBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_cow_customBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_cow_customBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
}
func test_validateMutation_slice_cow_customBacking_appendBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { (buffer) in
data.append(buffer.baseAddress!, count: buffer.count)
}
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customBacking_appendData() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customBacking_appendBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customBacking_appendSequence() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customBacking_appendContentsOf() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 1, 1, 1, 1, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customBacking_resetBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_replaceSubrange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_slice_cow_customBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBytes {
data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count)
}
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 1]))
}
}
func test_validateMutation_customMutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
func test_validateMutation_customMutableBacking_appendBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_customMutableBacking_appendData() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_customMutableBacking_appendBuffer() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_customMutableBacking_appendSequence() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_customMutableBacking_appendContentsOf() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_customMutableBacking_resetBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
data.resetBytes(in: 5..<8)
XCTAssertEqual(data.count, 10)
XCTAssertEqual(data[data.startIndex.advanced(by: 0)], 1)
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 6)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 7)], 0)
}
func test_validateMutation_customMutableBacking_replaceSubrange() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
func test_validateMutation_customMutableBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
func test_validateMutation_customMutableBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
func test_validateMutation_customMutableBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
func test_validateMutation_customMutableBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
func test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_customMutableBacking_appendBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customMutableBacking_appendData() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customMutableBacking_appendBuffer() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customMutableBacking_appendSequence() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customMutableBacking_appendContentsOf() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
func test_validateMutation_slice_customMutableBacking_resetBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
data.resetBytes(in: 5..<8)
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 2)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 3)], 0)
}
func test_validateMutation_slice_customMutableBacking_replaceSubrange() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
func test_validateMutation_slice_customMutableBacking_replaceSubrangeCountableRange() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
func test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBuffer() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
func test_validateMutation_slice_customMutableBacking_replaceSubrangeWithCollection() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
func test_validateMutation_slice_customMutableBacking_replaceSubrangeWithBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
func test_validateMutation_cow_customMutableBacking_withUnsafeMutableBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 5).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0xFF)
}
}
func test_validateMutation_cow_customMutableBacking_appendBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customMutableBacking_appendData() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customMutableBacking_appendBuffer() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customMutableBacking_appendSequence() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customMutableBacking_appendContentsOf() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_cow_customMutableBacking_resetBytes() {
var data = Data(referencing: AllOnesData(length: 10))
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data.count, 10)
XCTAssertEqual(data[data.startIndex.advanced(by: 0)], 1)
XCTAssertEqual(data[data.startIndex.advanced(by: 5)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 6)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 7)], 0)
}
}
func test_validateMutation_cow_customMutableBacking_replaceSubrange() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_cow_customMutableBacking_replaceSubrangeCountableRange() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBuffer() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_cow_customMutableBacking_replaceSubrangeWithCollection() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_cow_customMutableBacking_replaceSubrangeWithBytes() {
var data = Data(referencing: AllOnesData(length: 1))
data.count = 10
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [1, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_withUnsafeMutableBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
}
func test_validateMutation_slice_cow_customMutableBacking_appendBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_appendData() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
data.append(Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_appendBuffer() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.append($0) }
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_appendSequence() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
data.append(contentsOf: repeatElement(UInt8(0xFF), count: 2))
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_appendContentsOf() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
data.append(contentsOf: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 0, 0, 0, 0, 0xFF, 0xFF]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_resetBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
data.resetBytes(in: 5..<8)
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 2)], 0)
XCTAssertEqual(data[data.startIndex.advanced(by: 3)], 0)
}
}
func test_validateMutation_slice_cow_customMutableBacking_replaceSubrange() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeCountableRange() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let range: CountableRange<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: Data(bytes: [0xFF, 0xFF]))
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBuffer() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0) }
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithCollection() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
data.replaceSubrange(range, with: [0xFF, 0xFF])
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
}
func test_validateMutation_slice_cow_customMutableBacking_replaceSubrangeWithBytes() {
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<9]
holdReference(data) {
let range: Range<Int> = data.startIndex.advanced(by: 1)..<data.endIndex.advanced(by: -1)
let bytes: [UInt8] = [0xFF, 0xFF]
bytes.withUnsafeBufferPointer { data.replaceSubrange(range, with: $0.baseAddress!, count: $0.count) }
XCTAssertEqual(data, Data(bytes: [0, 0xFF, 0xFF, 0]))
}
}
#endif
func test_sliceHash() {
let base1 = Data(bytes: [0, 0xFF, 0xFF, 0])
let base2 = Data(bytes: [0, 0xFF, 0xFF, 0])
let base3 = Data(bytes: [0xFF, 0xFF, 0xFF, 0])
let sliceEmulation = Data(bytes: [0xFF, 0xFF])
XCTAssertEqual(base1.hashValue, base2.hashValue)
let slice1 = base1[base1.startIndex.advanced(by: 1)..<base1.endIndex.advanced(by: -1)]
let slice2 = base2[base2.startIndex.advanced(by: 1)..<base2.endIndex.advanced(by: -1)]
let slice3 = base3[base3.startIndex.advanced(by: 1)..<base3.endIndex.advanced(by: -1)]
XCTAssertEqual(slice1.hashValue, sliceEmulation.hashValue)
XCTAssertEqual(slice1.hashValue, slice2.hashValue)
XCTAssertEqual(slice2.hashValue, slice3.hashValue)
}
func test_slice_resize_growth() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<9]
data.resetBytes(in: data.endIndex.advanced(by: -1)..<data.endIndex.advanced(by: 1))
XCTAssertEqual(data, Data(bytes: [4, 5, 6, 7, 0, 0]))
}
/*
func test_sliceEnumeration() {
var base = DispatchData.empty
let bytes: [UInt8] = [0, 1, 2, 3, 4]
base.append(bytes.withUnsafeBytes { DispatchData(bytes: $0) })
base.append(bytes.withUnsafeBytes { DispatchData(bytes: $0) })
base.append(bytes.withUnsafeBytes { DispatchData(bytes: $0) })
let data = ((base as AnyObject) as! Data)[3..<11]
var regionRanges: [Range<Int>] = []
var regionData: [Data] = []
data.enumerateBytes { (buffer, index, _) in
regionData.append(Data(bytes: buffer.baseAddress!, count: buffer.count))
regionRanges.append(index..<index + buffer.count)
}
XCTAssertEqual(regionRanges.count, 3)
XCTAssertEqual(Range<Data.Index>(3..<5), regionRanges[0])
XCTAssertEqual(Range<Data.Index>(5..<10), regionRanges[1])
XCTAssertEqual(Range<Data.Index>(10..<11), regionRanges[2])
XCTAssertEqual(Data(bytes: [3, 4]), regionData[0]) //fails
XCTAssertEqual(Data(bytes: [0, 1, 2, 3, 4]), regionData[1]) //passes
XCTAssertEqual(Data(bytes: [0]), regionData[2]) //fails
}
*/
func test_sliceInsertion() {
// https://bugs.swift.org/browse/SR-5810
let baseData = Data([0, 1, 2, 3, 4, 5])
var sliceData = baseData[2..<4]
let sliceDataEndIndexBeforeInsertion = sliceData.endIndex
let elementToInsert: UInt8 = 0x07
sliceData.insert(elementToInsert, at: sliceData.startIndex)
XCTAssertEqual(sliceData.first, elementToInsert)
XCTAssertEqual(sliceData.startIndex, 2)
XCTAssertEqual(sliceDataEndIndexBeforeInsertion, 4)
XCTAssertEqual(sliceData.endIndex, sliceDataEndIndexBeforeInsertion + 1)
}
func test_sliceDeletion() {
// https://bugs.swift.org/browse/SR-5810
let baseData = Data([0, 1, 2, 3, 4, 5, 6, 7])
let sliceData = baseData[2..<6]
var mutableSliceData = sliceData
let numberOfElementsToDelete = 2
let subrangeToDelete = mutableSliceData.startIndex..<mutableSliceData.startIndex.advanced(by: numberOfElementsToDelete)
mutableSliceData.removeSubrange(subrangeToDelete)
XCTAssertEqual(sliceData[sliceData.startIndex + numberOfElementsToDelete], mutableSliceData.first)
XCTAssertEqual(mutableSliceData.startIndex, 2)
XCTAssertEqual(mutableSliceData.endIndex, sliceData.endIndex - numberOfElementsToDelete)
}
func test_validateMutation_slice_withUnsafeMutableBytes_lengthLessThanLowerBound() {
var data = Data(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[4..<6]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data, Data(bytes: [4, 0xFF]))
}
func test_validateMutation_slice_immutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
var data = Data(referencing: NSData(bytes: "hello world", length: 11))[4..<6]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
#if !DARWIN_COMPATIBILITY_TESTS // Crashes on native Darwin
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
var data = base[4..<6]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
#endif
}
func test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<6]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
}
func test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
#if !DARWIN_COMPATIBILITY_TESTS // Crashes on native Darwin
var base = Data(referencing: AllOnesData(length: 1))
base.count = 10
var data = base[4..<6]
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
ptr.advanced(by: 1).pointee = 0xFF
}
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
#endif
}
}
| apache-2.0 |
netyouli/SexyJson | SexyJson/Model/Test.swift | 1 | 1754 | //
// Test.swift
// SexyJson
//
// Created by WHC on 2018/4/10.
// Copyright © 2018年 WHC. All rights reserved.
//
import Foundation
/**
* Copyright 2018 wuhaichao.com
* Auto-generated:2018/4/10 下午3:20:26
*
* @author wuhaichao.com (whc)
* @website http://wuhaichao.com
* @github https://github.com/netyouli
*/
//MARK: - hotelListFilterItem -
struct HotelListFilterItem:SexyJson {
var hotelStyle: String?
mutating func sexyMap(_ map: [String : Any]) {
hotelStyle <<< map["hotelStyle"]
}
}
//MARK: - dataList -
struct DataList:SexyJson {
var name: String?
var isDefault: Bool = false
var hotelListFilterItem: HotelListFilterItem?
var dataId: Int = 0
var tagList: [Any]?
public mutating func sexyMap(_ map: [String : Any]) {
name <<< map["name"]
isDefault <<< map["isDefault"]
hotelListFilterItem <<< map["hotelListFilterItem"]
dataId <<< map["dataId"]
tagList <<< map["tagList"]
}
}
//MARK: - queryHotelObj -
struct QueryHotelObj:SexyJson {
var dataList: [DataList]?
public mutating func sexyMap(_ map: [String : Any]) {
dataList <<< map["dataList"]
}
}
//MARK: - BaseClass -
struct BaseClass:SexyJson {
var queryHotelObj: QueryHotelObj?
var resultType: Int = 0
var message: String?
public mutating func sexyMap(_ map: [String : Any]) {
queryHotelObj <<< map["queryHotelObj"]
resultType <<< map["resultType"]
message <<< map["message"]
}
}
| mit |
apple/swift-tools-support-core | Sources/TSCUtility/BuildFlags.swift | 1 | 1252 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
// FIXME: This belongs somewhere else, but we don't have a layer specifically
// for BuildSupport style logic yet.
//
/// Build-tool independent flags.
@available(*, deprecated, message: "replace with SwiftPM `PackageModel.BuildFlags`")
public struct BuildFlags: Encodable {
/// Flags to pass to the C compiler.
public var cCompilerFlags: [String]
/// Flags to pass to the C++ compiler.
public var cxxCompilerFlags: [String]
/// Flags to pass to the linker.
public var linkerFlags: [String]
/// Flags to pass to the Swift compiler.
public var swiftCompilerFlags: [String]
public init(
xcc: [String]? = nil,
xcxx: [String]? = nil,
xswiftc: [String]? = nil,
xlinker: [String]? = nil
) {
cCompilerFlags = xcc ?? []
cxxCompilerFlags = xcxx ?? []
linkerFlags = xlinker ?? []
swiftCompilerFlags = xswiftc ?? []
}
}
| apache-2.0 |
DavidSkrundz/Lua | Sources/Lua/Value/Table.swift | 1 | 2086 | //
// Table.swift
// Lua
//
/// Represent a table within Lua
public class Table {
private let lua: Lua
internal let reference: Reference
public var hashValue: Int {
return Int(self.reference.rawValue)
}
/// Create a new `Table` by popping the top value from the stack
internal init(lua: Lua) {
self.lua = lua
self.reference = self.lua.popWithReference()
}
deinit {
self.lua.release(self.reference)
}
/// Access a field within the `Table`
///
/// - Precondition: `key` cannot be `Nil`
public subscript(key: Value) -> Value {
get {
precondition(!(key is Nil))
self.lua.push(value: self)
self.lua.push(value: key)
self.lua.raw.getTable(atIndex: SecondIndex)
defer { self.lua.raw.pop(1) }
return self.lua.pop()
}
set {
precondition(!(key is Nil))
self.lua.push(value: self)
self.lua.push(value: key)
self.lua.push(value: newValue)
self.lua.raw.setTable(atIndex: ThirdIndex)
self.lua.raw.pop(1)
}
}
/// Calls the given closure on each key-value pair in the table
public func forEach(body: (TableKey, Value) -> Void) {
self.lua.push(value: self)
self.lua.raw.pushNil()
while self.lua.raw.next(atIndex: SecondIndex) {
let value = self.lua.pop()
let key = self.lua.get(atIndex: TopIndex)
body(TableKey(key), value)
}
}
/// Uses `self.forEach` to construct a `[TableKey : Value]` and returns it
public func toDictionary() -> [TableKey : Value] {
var dict = [TableKey : Value]()
self.forEach { (key, value) in dict[key] = value }
return dict
}
/// Perform equality between two `Table`s
///
/// - Parameter rhs: The `Table` to compare to
///
/// - Returns: `true` if the `Table`s are the same object
fileprivate func isEqual(to other: Table) -> Bool {
self.lua.push(value: self)
self.lua.push(value: other)
defer { self.lua.raw.pop(2) }
return self.lua.raw.compare(index1: TopIndex, index2: SecondIndex,
comparator: .Equal)
}
}
extension Table: Equatable {}
public func ==(lhs: Table, rhs: Table) -> Bool {
return lhs.isEqual(to: rhs)
}
| lgpl-3.0 |
HakkiYigitYener/HurriyetApiSDKSwift | HurriyetApiSDKSwift/Classes/Models/HAPath.swift | 1 | 610 | //
// HAPath.swift
// HurriyetApiSwiftSDK
//
// Created by Hakkı Yiğit Yener on 17.12.2016.
// Copyright © 2016 Hurriyet. All rights reserved.
//
import UIKit
class HAPath: NSObject {
//Dizin id'sini temsil eder.
public var Id:String? = ""
//Dizini temsil eder.
public var Path:String? = ""
//Dizin başlığını temsil eder.
public var Title:String? = ""
init(dictionary: Dictionary<String, Any>) {
super.init()
Id = dictionary["Id"] as! String?;
Path = dictionary["Path"] as! String?
Title = dictionary["Title"] as! String?
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/25781-swift-parser-parseexprcallsuffix.swift | 13 | 242 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init{return m(
class
case,
| apache-2.0 |
PrinceChen/DouYu | DouYu/DouYu/Classes/Home/View/CollectionGameCell.swift | 1 | 901 | //
// CollectionGameCell.swift
// DouYu
//
// Created by prince.chen on 2017/3/3.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionGameCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titelLabel: UILabel!
var baseGame: BaseGameModel? {
didSet {
titelLabel.text = baseGame?.tag_name
if let iconURL = URL(string: baseGame?.icon_url ?? "") {
iconImageView.kf.setImage(with: iconURL)
} else {
iconImageView.image = UIImage(named: "dyla_btn_more")
}
}
}
// var group: AnchorGroup? {
//
// }
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| mit |
calosth/Instagram | Instragram/ViewController.swift | 1 | 514 | //
// ViewController.swift
// Instragram
//
// Created by Carlos Linares on 4/29/15.
// Copyright (c) 2015 Carlos Linares. 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.
}
}
| mit |
stone-payments/onestap-sdk-ios | OnestapSDKTests/RedirectHandlerTests.swift | 1 | 1091 | //
// RedirectHandlerTests.swift
// OnestapSDK
//
// Created by Munir Wanis on 22/09/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import XCTest
@testable import OnestapSDK
class RedirectHandlerTests: 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 testRedirectHandleImplementationConfigNotFoundError() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
do {
_ = try RedirectHandlerImplementation(bundle: nil)
} catch {
switch error {
case OSTErrors.plistNotFound:
XCTAssertTrue(true)
default:
XCTFail()
}
}
}
}
| apache-2.0 |
Zeacone/FXSVG | src/SVGElement.swift | 1 | 3796 | //
// SVGElement.swift
// iPet
//
// Created by mac on 2017/10/26.
// Copyright © 2017年 zeacone. All rights reserved.
//
import UIKit
struct Stack<T> {
var items = [T]()
mutating func pop() -> T {
return items.removeLast()
}
mutating func push(_ item: T) {
items.append(item)
}
func top() -> T? {
return items.last
}
}
class SVGElement: NSObject {
// Element's parent
var parent: SVGElement?
// Element's children
var children = [SVGElement]()
// Element's name
var name: String!
var attr: [String: String]!
/// Element's id to find this element easily.
var id: String?
var clipPath: String?
var filter: String?
var fillRule: String?
var transform: CGAffineTransform?
/// Element's title. If this property is not nil, then we should show a text element on it.
var title: String?
/// A bezier path to draw element.
lazy var path: UIBezierPath = UIBezierPath()
/// Stroke color
var strokeColor: UIColor?
/// Fill color
var fillColor: UIColor?
/// A property to decide if this element is selectable.
var clickable: Bool = false
/// A transform string to generate real transform.
var transformString: String? {
get {
return nil
}
set {
if let value = newValue {
let transform = SVGTransformParser.transfrom(value)
self.path.apply(transform)
}
}
}
/// I don't know how this works.
var className: String?
/// Initializer
///
/// - Parameter attr: Some properties.
required init(name: String, attr: [String: String]) {
super.init()
self.name = name
self.readProperty(attr)
self.draw(attr: attr)
}
/// Read some public properties from attribute collections.
///
/// - Parameter attr: Some properties.
func readProperty(_ attr: [String: String]) {
self.title = attr["title"]
self.id = attr["id"]
self.strokeColor = self.hexColorString(attr["stroke"])
self.fillColor = self.hexColorString(attr["fill"])
self.transformString = attr["transform"]
self.className = attr["class"]
self.filter = attr["filter"]
self.clipPath = attr["clip-path"]
}
/// Convert hex string to UIColor.
///
/// - Parameter hex: A hex string.
/// - Returns: Destination color.
func hexColorString(_ hex: String?) -> UIColor {
guard var string = hex else { return UIColor.clear }
if string.hasPrefix("#") {
string.removeFirst(1)
}
if string.hasPrefix("0x") {
string.removeFirst(2)
}
let scanner = Scanner(string: string)
var hexColor: UInt32 = 0
if scanner.scanHexInt32(&hexColor) {
return self.hexColor(Int(hexColor))
}
return UIColor.clear
}
/// Parse color from a hex integer.
///
/// - Parameter hex: A hex integer.
/// - Returns: Destination color.
func hexColor(_ hex: Int) -> UIColor {
let red = CGFloat(hex >> 16 & 0xFF) / 255.0
let green = CGFloat(hex >> 8 & 0xFF) / 255.0
let blue = CGFloat(hex & 0xFF) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
/// Provide a super function but do nothing. It will be implemented by it's subclass.
///
/// - Parameter attr: Some properties.
func draw(attr: [String: String]) {
}
}
| gpl-3.0 |
torinmb/Routinely | Routinely/TaskTableViewController.swift | 1 | 6918 | //
// TaskTableViewController.swift
// Routinely
//
// Created by Torin Blankensmith on 4/7/15.
// Copyright (c) 2015 Torin Blankensmith. All rights reserved.
import UIKit
class TaskTableViewController: RoutineTableViewController {
var tasks : [String]
required init(coder aDecoder: NSCoder) {
tasks = [String]()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: false)
self.tableView.backgroundColor = UIColor(white: 0, alpha: 1)
let pinch = UIPinchGestureRecognizer(target: self, action: "handlePinch:")
self.tableView.addGestureRecognizer(pinch)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return tasks.count + 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("start", forIndexPath: indexPath) as! UITableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.textLabel?.backgroundColor = UIColor.clearColor()
cell.delegate = self
cell.routineItem = Routine(text: tasks[indexPath.row - 1])
return cell
}
// Configure the cell...
}
// MARK: - pinch methods
struct TouchPoints {
var upper: CGPoint
var lower: CGPoint
}
// the indices of the upper and lower cells that are being pinched
var upperCellIndex = -100
var lowerCellIndex = -100
// the location of the touch points when the pinch began
var initialTouchPoints: TouchPoints!
// indicates that the pinch was big enough to cause a new item to be added
var pinchExceededRequiredDistance = false
var pinchInProgress = false
func handlePinch(recognizer: UIPinchGestureRecognizer) {
switch recognizer.state {
case .Began:
performSegueWithIdentifier("unwindSegue", sender: self)
// pinchStarted(recognizer)
case .Changed :
if pinchInProgress && recognizer.numberOfTouches() == 2 {
pinchChanged(recognizer)
}
case .Ended:
pinchEnded(recognizer)
default:
break
}
}
func pinchStarted(recognizer: UIPinchGestureRecognizer) {
}
func pinchChanged(recognizer: UIPinchGestureRecognizer) {
}
func pinchEnded(recognizer: UIPinchGestureRecognizer) {
}
// returns the two touch points, ordering them to ensure that
// upper and lower are correctly identified.
func getNormalizedTouchPoints(recognizer: UIGestureRecognizer) -> TouchPoints {
var pointOne = recognizer.locationOfTouch(0, inView: tableView)
var pointTwo = recognizer.locationOfTouch(1, inView: tableView)
// ensure pointOne is the top-most
if pointOne.y > pointTwo.y {
let temp = pointOne
pointOne = pointTwo
pointTwo = temp
}
return TouchPoints(upper: pointOne, lower: pointTwo)
}
func viewContainsPoint(view: UIView, point: CGPoint) -> Bool {
let frame = view.frame
return (frame.origin.y < point.y) && (frame.origin.y + (frame.size.height) > point.y)
}
// override func cellDidBeginEditing(editingCell: TableViewCell) {
// cellSaveState = editingCell.label.text
// }
// override func cellDidEndEditing(editingCell: TableViewCell) {
// if editingCell.label.text != cellSaveState {
// let index = find(tasks, cellSaveState)
//// routineItems[index!] = editingCell.label.text
// }
// }
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "presentCardViewSegue" {
let view = segue.destinationViewController as! CardViewController
NSLog(navigationItem.title!)
view.groupTitle = navigationItem.title!
NSLog(tasks.count.description)
view.tasks = self.tasks
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
}
| mit |
tbaranes/SwiftyUtils | Tests/Protocols/Swift/AnyOptionalTests.swift | 1 | 582 | //
// AnyOptionalTests.swift
// SwiftyUtils
//
// Created by Tom Baranes on 25/04/2020.
// Copyright © 2020 Tom Baranes. All rights reserved.
//
import XCTest
import SwiftyUtils
final class AnyOptionalTests: XCTestCase {
// MARK: Life cycle
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
// MARK: - Tests
extension AnyOptionalTests {
func testIsNil() {
var string: String?
XCTAssertTrue(string.isNil)
string = "test"
XCTAssertFalse(string.isNil)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/07932-swift-modulefile-getdecl.swift | 11 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
let a {
init {
class
case c,
class
}
| mit |
NestedWorld/NestedWorld-iOS | nestedworld/nestedworldTests/UserTestsProtocol.swift | 1 | 807 | //
// UserTestsProtocol.swift
// nestedworld
//
// Created by Jean-Antoine Dupont on 26/04/2016.
// Copyright © 2016 NestedWorld. All rights reserved.
//
protocol UserTestsProtocol
{
/*
// MARK: Default value
var email: String { get set }
var nickname: String { get set }
var gender: String { get set }
var birthDate:String { get set }
var city: String { get set }
var background: String { get set }
var avatar: String { get set }
var registerDate: String { get set }
var isActive: Bool { get set }
*/
func testAll()
/*
func testEmail()
func testNickname()
func testGender()
func testBirthDate()
func testCity()
func testBackground()
func testAvatar()
func testRegisterDate()
func testIsActive()
*/
} | mit |
antlr/antlr4 | runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift | 4 | 2190 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
public class SingletonPredictionContext: PredictionContext {
public final let parent: PredictionContext?
public final let returnState: Int
init(_ parent: PredictionContext?, _ returnState: Int) {
//TODO assert
//assert ( returnState=ATNState.INVALID_STATE_NUMBER,"Expected: returnState!/=ATNState.INVALID_STATE_NUMBER");
self.parent = parent
self.returnState = returnState
super.init(parent.map { PredictionContext.calculateHashCode($0, returnState) } ?? PredictionContext.calculateEmptyHashCode())
}
public static func create(_ parent: PredictionContext?, _ returnState: Int) -> SingletonPredictionContext {
if returnState == PredictionContext.EMPTY_RETURN_STATE && parent == nil {
// someone can pass in the bits of an array ctx that mean $
return EmptyPredictionContext.Instance
}
return SingletonPredictionContext(parent, returnState)
}
override
public func size() -> Int {
return 1
}
override
public func getParent(_ index: Int) -> PredictionContext? {
assert(index == 0, "Expected: index==0")
return parent
}
override
public func getReturnState(_ index: Int) -> Int {
assert(index == 0, "Expected: index==0")
return returnState
}
override
public var description: String {
let up = parent?.description ?? ""
if up.isEmpty {
if returnState == PredictionContext.EMPTY_RETURN_STATE {
return "$"
}
return String(returnState)
}
return String(returnState) + " " + up
}
}
public func ==(lhs: SingletonPredictionContext, rhs: SingletonPredictionContext) -> Bool {
if lhs === rhs {
return true
}
if lhs.hashValue != rhs.hashValue {
return false
}
if lhs.returnState != rhs.returnState {
return false
}
return lhs.parent == rhs.parent
}
| bsd-3-clause |
tingkerians/master | doharmony/LocalTableViewCell.swift | 1 | 783 | //
// LocalTableViewCell.swift
// doharmony
//
// Created by Eleazer Toluan on 2/11/16.
// Copyright © 2016 Eleazer Toluan. All rights reserved.
//
import UIKit
class LocalTableViewCell: UITableViewCell {
@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var TitleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBAction func deleteTracks(sender: AnyObject) {
print("delete")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor .clearColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| unlicense |
Mogendas/apiproject | apiproject/SettingsVC.swift | 1 | 4109 | //
// SettingsVC.swift
// apiproject
//
// Created by Johan Wejdenstolpe on 2017-05-15.
// Copyright © 2017 Johan Wejdenstolpe. All rights reserved.
//
import UIKit
class SettingsVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let searchResults = (1...10).map { $0 * 5 }
let searchRadius = (5...20).map { $0 * 100 }
let moveRadius = (1...10).map { $0 * 50 }
let userSettings = UserDefaults()
var pickerArray: [Int] = [Int]()
var selectedRow: Int = 0
@IBOutlet weak var settingsPickerView: UIPickerView!
@IBOutlet weak var lblSearchResult: UILabel!
@IBOutlet weak var lblSearchRadius: UILabel!
@IBOutlet weak var lblMoveRadius: UILabel!
@IBOutlet weak var pickerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
settingsPickerView.delegate = self
settingsPickerView.dataSource = self
if let results = userSettings.string(forKey: "SearchResult") {
lblSearchResult.text = "\(results) st"
}
if let radius = userSettings.string(forKey: "SearchRadius") {
lblSearchRadius.text = "\(radius) m"
}
if let radiusMove = userSettings.string(forKey: "MoveRadius") {
lblMoveRadius.text = "\(radiusMove) m"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func searchResultTapped(_ sender: UITapGestureRecognizer) {
pickerArray = searchResults
if let results = Int(userSettings.string(forKey: "SearchResult")!) {
if let row = pickerArray.index(of: results) {
selectedRow = row
}
}
pickerLabel.text = "Välj antal sökresultat"
showPickerView()
}
@IBAction func viewTap(_ sender: UITapGestureRecognizer) {
settingsPickerView.isHidden = true
pickerLabel.isHidden = true
}
@IBAction func searchRadiusTapped(_ sender: UITapGestureRecognizer) {
pickerArray = searchRadius
if let radius = Int(userSettings.string(forKey: "SearchRadius")!) {
if let row = pickerArray.index(of: radius) {
selectedRow = row
}
}
pickerLabel.text = "Välj sökradie"
showPickerView()
}
@IBAction func moveRadiusTapped(_ sender: UITapGestureRecognizer) {
pickerArray = moveRadius
if let radiusMove = Int(userSettings.string(forKey: "MoveRadius")!) {
if let row = pickerArray.index(of: radiusMove) {
selectedRow = row
}
}
pickerLabel.text = "Välj uppdateringsradie"
showPickerView()
}
func showPickerView(){
settingsPickerView.reloadAllComponents()
settingsPickerView.selectRow(selectedRow, inComponent: 0, animated: true)
pickerLabel.isHidden = false
settingsPickerView.isHidden = false
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerArray.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(pickerArray[row])"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerArray.last == 50{
lblSearchResult.text = "\(pickerArray[row]) st"
userSettings.setValue("\(pickerArray[row])", forKey: "SearchResult")
}
if pickerArray.last == 2000{
lblSearchRadius.text = "\(pickerArray[row]) m"
userSettings.setValue("\(pickerArray[row])", forKey: "SearchRadius")
}
if pickerArray.last == 500{
lblMoveRadius.text = "\(pickerArray[row]) m"
userSettings.setValue("\(pickerArray[row])", forKey: "MoveRadius")
}
}
}
| gpl-3.0 |
terflogag/BadgeSegmentControl | Example/Exemple/ViewController.swift | 1 | 8367 | //
// ViewController.swift
// Exemple
//
// Created by Florian Gabach on 22/08/2017.
// Copyright © 2017 Florian Gabach. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK : - IBOutlet
@IBOutlet weak var segmentView: BadgeSegmentControl!
@IBOutlet weak var simpleSegmentView: BadgeSegmentControl!
@IBOutlet weak var imageSegmentView: BadgeSegmentControl!
@IBOutlet weak var simpleSegmentViewWithBar: BadgeSegmentControl!
// MARK: - Var
fileprivate let mainColor = UIColor(red:1.00, green:0.62, blue:0.22, alpha:1.00)
fileprivate var firstBadgeValue: Int = 0
fileprivate var secondBadgeValue: Int = 0
fileprivate var programaticallySegmentedControl: BadgeSegmentControl?
fileprivate let firstSegmentName = "Emojiraf"
fileprivate let secondSegmentName = "Messages"
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Background color
self.view.backgroundColor = self.mainColor
// Prepare two segment for demo
self.prepareTextAndImageSegment()
self.prepareSimpleSegment()
self.prepareOnlyImageSegment()
self.addWithoutStoryboard()
self.prepareSegmentWithBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Prepare segment
/// Prepare the first segment without image and badge
func prepareSimpleSegment() {
self.simpleSegmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.simpleSegmentView.addSegmentWithTitle(self.firstSegmentName)
self.simpleSegmentView.addSegmentWithTitle(self.secondSegmentName)
self.simpleSegmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.simpleSegmentView.selectedSegmentIndex = 0
}
/// Prepare the second segment with image and badge
func prepareTextAndImageSegment() {
self.segmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.segmentView.addSegmentWithTitle(self.firstSegmentName,
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white))
self.segmentView.addSegmentWithTitle(self.secondSegmentName,
onSelectionImage: UIImage(named: "message")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white))
self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.segmentView.selectedSegmentIndex = 0
}
/// Prepare the second segment with image and badge
func prepareOnlyImageSegment() {
self.imageSegmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.imageSegmentView.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white))
self.imageSegmentView.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "message")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white))
self.imageSegmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.imageSegmentView.selectedSegmentIndex = 0
}
/// Prepare the segment with bar
func prepareSegmentWithBar() {
self.simpleSegmentViewWithBar.segmentAppearance = SegmentControlBarAppearence.appearance()
// Add segments
self.simpleSegmentViewWithBar.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white.withAlphaComponent(0.3)))
self.simpleSegmentViewWithBar.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white.withAlphaComponent(0.3)))
self.simpleSegmentViewWithBar.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.simpleSegmentViewWithBar.selectedSegmentIndex = 0
}
func addWithoutStoryboard() {
let padding: CGFloat = 50
self.programaticallySegmentedControl = BadgeSegmentControl(frame: CGRect(x: padding / 2,
y: self.view.frame.height - (padding * 2),
width: self.view.frame.width - padding,
height: padding))
self.programaticallySegmentedControl?.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.programaticallySegmentedControl?.addSegmentWithTitle("First")
self.programaticallySegmentedControl?.addSegmentWithTitle("Second")
self.programaticallySegmentedControl?.addTarget(self,
action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.programaticallySegmentedControl?.selectedSegmentIndex = 0
// Add to subview
if let segmentControl = self.programaticallySegmentedControl {
self.view.addSubview(segmentControl)
}
}
// MARK: - Action
@IBAction func doUpdateFirstBadgeClick(_ sender: Any) {
self.firstBadgeValue += 1
self.segmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
self.imageSegmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
self.simpleSegmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
}
@IBAction func doUpdateSecondBadgeClick(_ sender: Any) {
self.secondBadgeValue += 1
self.segmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
self.imageSegmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
self.simpleSegmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
}
// Segment selector for .ValueChanged
@objc func selectSegmentInSegmentView(segmentView: BadgeSegmentControl) {
print("Select segment at index: \(segmentView.selectedSegmentIndex)")
}
}
| mit |
plushcube/Learning | UI/CollectionViewPlayground/CollectionViewPlayground/CollectionViewLayout.swift | 1 | 246 | //
// CollectionViewLayout.swift
// CollectionViewPlayground
//
// Created by Andrey & Mari on 29/11/2016.
// Copyright © 2016 Andrey & Mari. All rights reserved.
//
import UIKit
class CollectionViewLayout: UICollectionViewFlowLayout {
}
| mit |
mitchellporter/Cheetah | Cheetah/CheetahLayerProperties.swift | 1 | 3261 | //
// CheetahLayerProperties.swift
// Cheetah
//
// Created by Suguru Namura on 2015/08/20.
// Copyright © 2015年 Suguru Namura.
//
import UIKit
class CheetahLayerPositionProperty: CheetahCGPointProperty {
init(view: UIView!, position: CGPoint, relative: Bool = false) {
super.init()
self.view = view
self.relative = relative
to = position
}
override func prepare() {
super.prepare()
from = view.layer.position
}
override func update() {
view.layer.position = calculateCGPoint(from: from, to: toCalc)
}
}
class CheetahLayerRotationProperty: CheetahCGFloatProperty {
var last: CGFloat = 0
init(view: UIView!, rotation: CGFloat, relative: Bool = false) {
super.init()
self.view = view
self.relative = relative
to = rotation
}
override func prepare() {
super.prepare()
from = atan2(view.layer.transform.m12, view.layer.transform.m11)
}
override func update() {
let curr = calculateCGFloat(from: from, to: toCalc)
transform = CATransform3DMakeRotation(curr, 0, 0, 1)
}
}
class CheetahLayerScaleProperty: CheetahCGPointProperty {
var last: CGPoint = CGPointZero
init(view: UIView!, scale: CGPoint) {
super.init()
self.view = view
to = scale
}
override func prepare() {
super.prepare()
let t = view.layer.transform
from.x = sqrt((t.m11 * t.m11) + (t.m12 * t.m12) + (t.m13 * t.m13))
from.y = sqrt((t.m21 * t.m21) + (t.m22 * t.m22) + (t.m23 * t.m23))
}
override func update() {
let curr = calculateCGPoint(from: from, to: toCalc)
transform = CATransform3DMakeScale(curr.x, curr.y, 1)
}
}
class CheetahLayerBorderWidthProperty: CheetahCGFloatProperty {
init(view: UIView!, borderWidth: CGFloat) {
super.init()
self.view = view
to = borderWidth
}
override func prepare() {
super.prepare()
from = view.layer.borderWidth
}
override func update() {
view.layer.borderWidth = calculateCGFloat(from: from, to: toCalc)
}
}
class CheetahLayerCornerRadiusProperty: CheetahCGFloatProperty {
init(view: UIView!, cornerRadius: CGFloat) {
super.init()
self.view = view
to = cornerRadius
}
override func prepare() {
super.prepare()
from = view.layer.cornerRadius
}
override func update() {
view.layer.cornerRadius = calculateCGFloat(from: from, to: toCalc)
}
}
class CheetahLayerBorderColorProperty: CheetahUIColorProperty {
init(view: UIView!, borderColor: UIColor) {
super.init()
self.view = view
self.to = borderColor
}
override func prepare() {
super.prepare()
if let borderColor = view.layer.borderColor {
from = UIColor(CGColor: borderColor)
} else {
from = UIColor.blackColor()
}
}
override func update() {
let color = calculateUIColor(from: from, to: toCalc)
view.layer.borderColor = color.CGColor
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/00149-swift-typechecker-callwitness.swift | 65 | 488 | // 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: not %target-swift-frontend %s -typecheck
c
j)
func c<k>() -> (k, > k) -> k {
d h d.f 1, k(j, i)))
class k {
typealias h = h
| apache-2.0 |
twtstudio/WePeiYang-iOS | WePeiYang/Models/UserGuideViewController.swift | 1 | 3061 | //
// UserGuideViewController.swift
// WePeiYang
//
// Created by Allen X on 4/29/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
import UIKit
import SnapKit
let NOTIFICATION_GUIDE_DISMISSED = "NOTIFICATION_GUIDE_DISMISSED"
class UserGuideViewController: UIViewController {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var startButton: UIButton!
private var scrollView: UIScrollView!
private let numberOfPages = 4
override func viewDidLoad() {
super.viewDidLoad()
let frame = self.view.bounds
scrollView = UIScrollView(frame: frame)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
scrollView.contentOffset = CGPointZero
scrollView.contentSize = CGSize(width: frame.size.width * CGFloat(numberOfPages), height: frame.size.height)
scrollView.delegate = self
for page in 0 ..< numberOfPages {
var imageView = UIImageView()
imageView = UIImageView(image: UIImage(named: "guide\(page + 1)"))
imageView.frame = CGRect(x: frame.size.width * CGFloat(page), y: 0, width: frame.size.width, height: frame.size.height)
scrollView.addSubview(imageView)
}
self.view.insertSubview(scrollView, atIndex: 0)
startButton.layer.cornerRadius = 2.0
startButton.alpha = 0.0
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dismissSelf() {
self.dismissViewControllerAnimated(true, completion: {
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_GUIDE_DISMISSED, object: nil)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
// MARK: - UIScrollViewDelegate
extension UserGuideViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset
pageControl.currentPage = Int(offset.x / view.bounds.width)
if pageControl.currentPage == numberOfPages - 1 {
UIView.animateWithDuration(0.5) {
self.startButton.alpha = 1.0
}
} else {
UIView.animateWithDuration(0.2) {
self.startButton.alpha = 0.0
}
}
}
}
| mit |
PureSwift/Cacao | Sources/Cacao/UIMoveEvent.swift | 1 | 500 | //
// UIMoveEvent.swift
// Cacao
//
// Created by Alsey Coleman Miller on 11/20/17.
//
import Foundation
public final class UIMoveEvent: UIEvent {
public override var type: UIEventType { return .move }
public private(set) var focusHeading: UInt = 0
public private(set) var moveDirection: Int = 0
}
extension UIMoveEvent: UIResponderEvent {
@inline(__always)
func sendEvent(to responder: UIResponder) {
responder.move(with: self)
}
}
| mit |
brentdax/swift | test/IDE/complete_multiple_files.swift | 30 | 2065 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T1 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=T1
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T2 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=T2
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=TOP_LEVEL_1
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MODULE_SCOPED %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=MODULE_SCOPED
func testObjectExpr() {
fooObject.#^T1^#
}
// T1: Begin completions
// T1-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// T1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// T1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// T1-NEXT: End completions
func testGenericObjectExpr() {
genericFooObject.#^T2^#
}
// T2: Begin completions
// T2-NEXT: Keyword[self]/CurrNominal: self[#GenericFooStruct<Void>#]; name=self
// T2-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// T2-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// T2-NEXT: End completions
func topLevel1() {
#^TOP_LEVEL_1^#
}
// TOP_LEVEL_1: Begin completions
// TOP_LEVEL_1-NOT: ERROR
// TOP_LEVEL_1: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// TOP_LEVEL_1-NOT: true
// TOP_LEVEL_1-NOT: ERROR
// TOP_LEVEL_1: End completions
func moduleScoped() {
swift_ide_test.#^MODULE_SCOPED^#
}
// MODULE_SCOPED: Begin completions
// MODULE_SCOPED-NOT: ERROR
// MODULE_SCOPED: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// MODULE_SCOPED-NOT: ERROR
// MODULE_SCOPED: End completions
| apache-2.0 |
enisgayretli/EGFloatingTextField | EGFloatingTextField/Example/AppDelegate.swift | 4 | 2086 | //
// AppDelegate.swift
// Example
//
// Created by Mac HD on 9.08.2015.
//
//
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:.
}
}
| mit |
blockchain/My-Wallet-V3-iOS | SnapshotTestsHostApp/SceneDelegate.swift | 1 | 2676 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| lgpl-3.0 |
phitchcock/Immunize | iOSApp/iOSApp/SpringViewController.swift | 1 | 583 | //
// SpringViewController.swift
// iOSApp
//
// Created by Peter Hitchcock on 3/17/16.
// Copyright © 2016 Peter Hitchcock. All rights reserved.
//
import UIKit
class SpringViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL (string: "https://github.com/MengTo/Spring")
let requestObj = NSURLRequest(URL: url!)
webView.loadRequest(requestObj)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/Source/Sources.Common/Core/ServiceHandler.swift | 1 | 4478 | /*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* 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 author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:carlos@adaptive.me>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:ferran.vila.conesa@gmail.com>
*
* =====================================================================================================================
*/
import Foundation
import AdaptiveArpApi
public class ServiceHandler:NSObject {
/// Logging variable
let logger:ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge()
let loggerTag:String = "ServiceHandler"
/// Singleton instance
public class var sharedInstance : ServiceHandler {
struct Static {
static let instance : ServiceHandler = ServiceHandler()
}
return Static.instance
}
/// Constructor
public override init() {
}
/// Method that executes the method with the parameters from the APIRequest object send it by the Typescript. This method could return some data in the syncronous methods or execute some callback/listeners in the asyncronous ones
/// :param: apiRequest API Request object
/// :return: Data for returning the syncronous responses
public func handleServiceUrl(apiRequest:APIRequest) -> APIResponse {
if let bridgeType:String = apiRequest.getBridgeType() {
// Get the bridge
if let bridge:APIBridge = AppRegistryBridge.sharedInstance.getBridge(bridgeType) {
//logger.log(ILoggingLogLevel.Info, category: loggerTag, message: "ASYNC ID: \(apiRequest.getAsyncId())")
if apiRequest.getAsyncId() != -1 {
// let asyncId:Int64? = apiRequest.getAsyncId()
// async methods (executed in a background queue)
dispatch_async(GCD.backgroundQueue(), {
bridge.invoke(apiRequest)
/*if let result:APIResponse = bridge.invoke(apiRequest) {
} else {
self.logger.log(ILoggingLogLevel.Error, category: self.loggerTag, message: "There is an error executing the asyncronous method: \(apiRequest.getMethodName())")
}*/
})
} else {
// sync methods (executed in the main queue)
if let result:APIResponse = bridge.invoke(apiRequest) {
//logger.log(ILoggingLogLevel.Info, category: loggerTag, message: "SYNC SERVICE RESULT: \(result)")
return result
} else {
self.logger.log(ILoggingLogLevel.Error, category: self.loggerTag, message: "There is an error executing the syncronous method: \(apiRequest.getMethodName())")
}
}
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no bridge with the identifier: \(bridgeType)")
}
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no bridge type inside the API Request object")
}
// Asynchronous responses
return APIResponse(response: "", statusCode: 200, statusMessage: "Please see native platform log for details.")
}
}
| apache-2.0 |
zdima/ZDMatrixPopover | ZDMatrixPopover/ViewController.swift | 1 | 1626 | //
// ViewController.swift
// ZDMatrixPopover
//
// Created by Dmitriy Zakharkin on 1/7/17.
// Copyright © 2017 Dmitriy Zakharkin. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, ZDMatrixPopoverDelegate {
@IBOutlet var popover: ZDMatrixPopover!
@IBAction func clickMe(_ sender: Any) {
guard let button = sender as? NSView else {return}
if popover == nil {
popover = ZDMatrixPopover()
}
if popover!.isShown {
do { try popover!.close() } catch { print("exception:\(error)") }
return
}
let rightAlign: NSMutableParagraphStyle = NSMutableParagraphStyle()
rightAlign.alignment = .right
do {
try popover!.show(data: [
["1", "2 aa", "3", "x"],
["4 aaa", "5", NSAttributedString(string: "6", attributes: [
NSForegroundColorAttributeName: NSColor.red,
NSParagraphStyleAttributeName: rightAlign
]), "x"],
["7", "8", "9 a", "NSParagraphStyleAttributeName"]
], title: "Test popover with long title",
relativeTo: button.frame, of: button.superview!, preferredEdge: .maxY)
} catch { print("exception:\(error)") }
}
func getColumnFormatter(column: Int) -> Formatter? {
return nil
}
func getColumnAlignment(column: Int) -> NSTextAlignment {
if column == 2 {
return .right
}
return .left
}
func getColumnWidth(column: Int) -> Int {
return -1
}
}
| mit |
sammyd/LuggageLocator | Luggage LocatorTests/Luggage_LocatorTests.swift | 1 | 926 | //
// Luggage_LocatorTests.swift
// Luggage LocatorTests
//
// Created by Sam Davies on 30/08/2014.
// Copyright (c) 2014 VisualPutty. All rights reserved.
//
import UIKit
import XCTest
class Luggage_LocatorTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jackywpy/AudioKit | Tests/Tests/AKPluckedString.swift | 14 | 1473 | //
// main.swift
// AudioKit
//
// Created by Aurelius Prochazka on 11/30/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let note = Note()
let pluckedString = AKPluckedString()
pluckedString.frequency = note.frequency
setAudioOutput(pluckedString)
enableParameterLog(
"Frequency = ",
parameter: pluckedString.frequency,
timeInterval:20
)
}
}
class Note: AKNote {
var frequency = AKNoteProperty(value: 220, minimum: 110, maximum: 880)
override init() {
super.init()
addProperty(frequency)
}
convenience init(frequency startingFrequency: Float) {
self.init()
frequency.floatValue = startingFrequency
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let note1 = Note(frequency: 440)
note1.duration.floatValue = 6.0
let note2 = Note(frequency: 550)
note2.duration.floatValue = 6.0
let note3 = Note(frequency: 660)
note3.duration.floatValue = 6.0
let phrase = AKPhrase()
phrase.addNote(note1, atTime:0.5)
phrase.addNote(note2, atTime:1.0)
phrase.addNote(note3, atTime:1.5)
phrase.addNote(note2, atTime:2.0)
instrument.playPhrase(phrase)
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit |
uasys/swift | validation-test/compiler_crashers_fixed/01754-getselftypeforcontainer.swift | 65 | 498 | // 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: not %target-swift-frontend %s -typecheck
extension String {
var b = a<T> [[Any) {
func ^(b(")
}
protocol a {
typealias f : a<T>)
func a
publ
| apache-2.0 |
apple/swift | test/Constraints/swift_to_c_pointer_conversions_sil.swift | 10 | 1926 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -import-objc-header %S/Inputs/c_pointer_conversions.h %s -emit-sil -verify | %FileCheck %s
// REQUIRES: objc_interop
// Check that implicit conversions don't make expressions ambiguous
func test_overloaded_ref_is_not_ambiguous() {
func overloaded_func() -> UnsafeRawPointer { fatalError() }
func overloaded_func() -> UnsafePointer<Int8> { fatalError() }
func overloaded_mutable_func() -> UnsafeMutableRawPointer { fatalError() }
func overloaded_mutable_func() -> UnsafeMutablePointer<Int8> { fatalError() }
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G5_funcL0_SPys4Int8VGyF
// CHECK-NEXT: apply
const_char_ptr_func(overloaded_func()) // Ok
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G5_funcL0_SPys4Int8VGyF
// CHECK-NEXT: apply
const_opt_char_ptr_func(overloaded_func()) // Ok
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G13_mutable_funcL0_Spys4Int8VGyF
// CHECK-NEXT: apply
char_ptr_func(overloaded_mutable_func()) // Ok
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G13_mutable_funcL0_Spys4Int8VGyF
// CHECK-NEXT: apply
const_char_ptr_func(overloaded_mutable_func()) // Ok (picks UnsafeMutablePointer using implicit conversion)
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G13_mutable_funcL0_Spys4Int8VGyF
// CHECK-NEXT: apply
opt_char_ptr_func(overloaded_mutable_func()) // Ok
// CHECK: function_ref @$s34swift_to_c_pointer_conversions_sil36test_overloaded_ref_is_not_ambiguousyyF0G13_mutable_funcL0_Spys4Int8VGyF
// CHECK-NEXT: apply
const_opt_char_ptr_func(overloaded_mutable_func()) // Ok
}
| apache-2.0 |
wickwirew/FluentLayout | FluentLayout/LayoutDefaultControls.swift | 2 | 340 | import Foundation
import UIKit
public protocol LayoutDefaultControls {
func createLabel() -> UILabel
func createTitleLabel() -> UILabel
func createTextField() -> UITextField
func createTextView() -> UITextView
func createButton() -> UIButton
func createImage() -> UIImageView
}
| mit |
filom/ASN1Decoder | ASN1DecoderTests/ASN1DecoderExtensions.swift | 1 | 11107 | //
// ASN1DecoderExtensions.swift
// ASN1DecoderTests
//
// Copyright © 2020 Filippo Maguolo.
//
// 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 XCTest
@testable import ASN1Decoder
class ASN1DecoderX509Extensions: XCTestCase {
func getCertificate() throws -> X509Certificate {
let certificateData = samplePEMcertificate.data(using: .utf8)!
return try X509Certificate(data: certificateData)
}
func testAuthorityKeyIdentifier() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .authorityKeyIdentifier) as? X509Certificate.AuthorityKeyIdentifierExtension {
XCTAssertEqual(ext.keyIdentifier?.hexEncodedString(), "76028647F1F6A396C9BFD22D8E300E28398C588B")
XCTAssertEqual(ext.serialNumber?.hexEncodedString(), "5FA31045")
let certificateIssuer = ext.certificateIssuer
XCTAssertTrue(certificateIssuer?.contains("www.hostname.net") == true)
XCTAssertTrue(certificateIssuer?.contains("192.168.1.99") == true)
XCTAssertTrue(certificateIssuer?.contains("CN=EXTENSION TEST") == true)
}
} catch {
XCTFail("\(error)")
}
}
func testBasicConstraint() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .basicConstraints) as? X509Certificate.BasicConstraintExtension {
XCTAssertEqual(ext.isCA, true)
XCTAssertEqual(ext.pathLenConstraint, 3)
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testExtKeyUsage() {
do {
let x509 = try getCertificate()
let extKeyUsage = x509.extendedKeyUsage
XCTAssert(extKeyUsage.contains("1.3.6.1.5.5.7.3.2")) // TLS Web Client Authentication
XCTAssert(extKeyUsage.contains("1.3.6.1.5.5.7.3.4")) // E-mail Protection
XCTAssert(extKeyUsage.contains("1.3.6.1.4.1.311.10.3.4")) // Encrypted File System
} catch {
XCTFail("\(error)")
}
}
func testSubjectKeyIdentifier() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .subjectKeyIdentifier), let value = ext.value as? Data {
XCTAssertEqual(value.hexEncodedString(), "76028647F1F6A396C9BFD22D8E300E28398C588B")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testCertificatePolicies() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .certificatePolicies) as? X509Certificate.CertificatePoliciesExtension,
let policies = ext.policies {
XCTAssertEqual(policies[0].oid, "2.16.840.1.114412.2.1")
XCTAssertEqual(policies[0].qualifiers?[0].oid, "1.3.6.1.5.5.7.2.1")
XCTAssertEqual(policies[0].qualifiers?[0].value, "https://www.digicert.com/CPS")
XCTAssertEqual(policies[1].oid, "2.23.140.1.1")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testCertificateCRL() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .cRLDistributionPoints) as? X509Certificate.CRLDistributionPointsExtension,
let crls = ext.crls {
XCTAssertTrue(crls.contains("http://crl3.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crl"))
XCTAssertTrue(crls.contains("http://crl4.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crl"))
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testAuthorityInfoAccess() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .authorityInfoAccess) as? X509Certificate.AuthorityInfoAccessExtension,
let infoAccess = ext.infoAccess {
XCTAssertEqual(infoAccess[0].method, "1.3.6.1.5.5.7.48.1")
XCTAssertEqual(infoAccess[0].location, "http://ocsp.digicert.com")
XCTAssertEqual(infoAccess[1].method, "1.3.6.1.5.5.7.48.2")
XCTAssertEqual(infoAccess[1].location, "http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crt")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
let samplePEMcertificate = """
-----BEGIN CERTIFICATE-----
MIIDejCCAmKgAwIBAgIEX6MQRTANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5F
WFRFTlNJT04gVEVTVDAeFw0yMDExMDQyMDM0MTNaFw0yMTExMDQyMDM0MTNaMBkx
FzAVBgNVBAMMDkVYVEVOU0lPTiBURVNUMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEA0Q9U9Qd7ELpyx46zI6tL7UtIGDv48BaDKPO7JkcOyXE2OunO+/Rd
U7nrJP4t7KVoFDYAbzHfy3ViaCN/zzcHUQV5VLtg3ydaM3ruJ8lWZjj1nsH2hPxl
Rth6BttV64mRSUGc4w+OEoj/WMrErCS6uXs0Xjd/1+6h3MUnBua5pwhh59Wj9dCo
8Dn8gcsnFHy/GVMSfwSdSxWpuMfyPNfzQ4jffoneZv/xYpeYqFYdqs5cODqPsfqr
t8+T8Xh30pbDAVwQ0t7EMb+IH5oXIkujEDx+FViyqya/H+E5IXuMecFshD4Rebp5
f/9eE9Ct7BbfEeBOglzyYxB118+CswtcIwIDAQABo4HJMIHGMA8GA1UdEwQIMAYB
Af8CAQMwXAYDVR0jBFUwU4AUdgKGR/H2o5bJv9ItjjAOKDmMWIuhNaQbMBkxFzAV
BgNVBAMMDkVYVEVOU0lPTiBURVNUghB3d3cuaG9zdG5hbWUubmV0hwTAqAFjggRf
oxBFMB0GA1UdDgQWBBR2AoZH8fajlsm/0i2OMA4oOYxYizApBgNVHSUEIjAgBggr
BgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcKAwQwCwYDVR0PBAQDAgEGMA0GCSqG
SIb3DQEBCwUAA4IBAQBBVNtPF++n2KnL3sdezfx0BN1Thzz/k2D/amUnNcMNrUUj
T4k0Nu6ZQZPxnjH8VNAel7eFpRaLOS/zS9B63695lFnOOzJSKec2i0uyl9hRAMf5
HCoowRijyM9KfIHF8UQ2TSBJkL0Dbdhw6Yszq7JcGUj0g4mX/6c9MlsZFRfJ6S6I
mavDHwPsTf6Abz9em4rMF4HVoDpoky/srDh5JsFHZ37uiWtlyUpk87UgNZI+1xA+
3wCZU9yLMOYO7a2j7mLFSJobrN2BZPZYoFjto38XOkPpZxJSUWOPHekig1bH6Nwy
EBbHNd47ucLIF9f7UWBbBxnl1tjp8VVqX6IBsYuS
-----END CERTIFICATE-----
"""
let samplePEMcertificateApple = """
-----BEGIN CERTIFICATE-----
MIIIBTCCBu2gAwIBAgIQA44/ngnX7cexgD90p0w1qzANBgkqhkiG9w0BAQsFADB5
MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xGTAXBgNVBAsT
EHd3dy5kaWdpY2VydC5jb20xNjA0BgNVBAMTLURpZ2lDZXJ0IFNIQTIgRXh0ZW5k
ZWQgVmFsaWRhdGlvbiBTZXJ2ZXIgQ0EtMzAeFw0yMDEwMDcwMDAwMDBaFw0yMTEw
MDgxMjAwMDBaMIHHMR0wGwYDVQQPDBRQcml2YXRlIE9yZ2FuaXphdGlvbjETMBEG
CysGAQQBgjc8AgEDEwJVUzEbMBkGCysGAQQBgjc8AgECEwpDYWxpZm9ybmlhMREw
DwYDVQQFEwhDMDgwNjU5MjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3Ju
aWExEjAQBgNVBAcTCUN1cGVydGlubzETMBEGA1UEChMKQXBwbGUgSW5jLjEWMBQG
A1UEAxMNd3d3LmFwcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMobHCF4FT1Az6N5P53PslOrqUH/PgahKWmKBEae+8QNVnrK5oDnr8bAv4tg
ccqa6HYMBsibd7jzG+p+5zqEy6OIpZMEP2lmd8+uBtHZ4RAIeuAkmOdWlw9zaHtN
aUYoJv8FgQzA2vwhcYFlmjnJ6Wg2NgJfgYC3fopb/jTQznYt2Ys+1BPA7OsPLHet
Hnsg9tqSmP2J86fLUxYusLlivsjDKEDPjFxhd4+SPS8j8gqrZYIiuJjOusgAleRn
NG525dHTLVGRvO/AyN74e8xGRQB22cswMelW/Q5o9Db5G1+IYWKPYKjeQ3tcwRVz
1AYSboWbUJwkv1/89GiVZ9W/RHECAwEAAaOCBDgwggQ0MB8GA1UdIwQYMBaAFM+F
8bw4GHg6VTP0VsrAaa13bruTMB0GA1UdDgQWBBQmH7tn0rlB7VcS548sc00Xi2tw
jjA8BgNVHREENTAzghBpbWFnZXMuYXBwbGUuY29tgg13d3cuYXBwbGUuY29tghB3
d3cuYXBwbGUuY29tLmNuMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEF
BQcDAQYIKwYBBQUHAwIwgaUGA1UdHwSBnTCBmjBLoEmgR4ZFaHR0cDovL2NybDMu
ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkV4dGVuZGVkVmFsaWRhdGlvblNlcnZl
ckNBLTMuY3JsMEugSaBHhkVodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNl
cnRTSEEyRXh0ZW5kZWRWYWxpZGF0aW9uU2VydmVyQ0EtMy5jcmwwSwYDVR0gBEQw
QjA3BglghkgBhv1sAgEwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNl
cnQuY29tL0NQUzAHBgVngQwBATCBigYIKwYBBQUHAQEEfjB8MCQGCCsGAQUFBzAB
hhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wVAYIKwYBBQUHMAKGSGh0dHA6Ly9j
YWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJFeHRlbmRlZFZhbGlkYXRp
b25TZXJ2ZXJDQS0zLmNydDAJBgNVHRMEAjAAMIIB9gYKKwYBBAHWeQIEAgSCAeYE
ggHiAeAAdwD2XJQv0XcwIhRUGAgwlFaO400TGTO/3wwvIAvMTvFk4wAAAXUE5RIw
AAAEAwBIMEYCIQDfwCPGlYS5Fzl5E9qSJfXEJZKk3Bocy3gRZ3VnSetQ9wIhAJTV
W7NpwxMvgje6f3Bl4pD/8LONvdNOfQhA/RRf/mZgAHUAXNxDkv7mq0VEsV6a1Fbm
EDf71fpH3KFzlLJe5vbHDsoAAAF1BOUShAAABAMARjBEAiBym6EmF1g6CDmqOaKZ
LiOpKJ310wVgWfezVSZoqZCUTQIgbMkp3ZqwIJlxECUiFNCcWvOvXDnRjTmZRNnU
gl9wFj8AdgBWFAaaL9fC7NP14b1Esj7HRna5vJkRXMDvlJhV1onQ3QAAAXUE5RQW
AAAEAwBHMEUCIQDtvAk0Fs6QOodDRWXG8pwviOAD0A3P8MrepljlmvCC+AIgaYPc
dA2gwQbMR+muIHIw6zzpDE2rgBYUmmirGfGXGq8AdgCkuQmQtBhYFIe7E6LMZ3AK
PDWYBPkb37jjd80OyA3cEAAAAXUE5RThAAAEAwBHMEUCIQDVJYiGuX96WaI2ry/P
uChTJsmpiTxPwJItHL0YMJ+HmQIga60LicX5sIxA7jVWLe1skZQvA8SM8dTY9mjf
5qpP9U8wDQYJKoZIhvcNAQELBQADggEBACLAg6hBZGjc2m3vB0YyMlclnv5dQ0vy
F8JfHobkrFQ7O+mW35LiDY/ZIF9KBLGY5eOtHSYX8+Ktt1bcRilwq9Vjip80Atb4
Wpzq9tM6zFx+oxVGv1YsOWdCir94838tP0d0ILqoyqUWVu6HgyJBu3ZEABaSZcIx
4TjJ9LhOtzyO44mcHqgNXiA7IdK3TPs39iAmVx3+3PQmwjbGGjKgR0rORIGUuCa6
YVqR0ad1wWG4M24HgTR/+d40C4JNVY3FFptUvCCw4yD5Jzk2duFsAmC9bZxpTbzc
hoOQIW3CEt8hUquiqBBvOv+7YI3JrMHBsLt9T44YYiKC+XkFnh7yG9E=
-----END CERTIFICATE-----
"""
}
| mit |
googleads/googleads-mobile-ios-examples | Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift | 1 | 5279 | //
// Copyright (C) 2015 Google, Inc.
//
// 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 GoogleMobileAds
import UIKit
class ViewController: UIViewController, GADFullScreenContentDelegate {
enum GameState: NSInteger {
case notStarted
case playing
case paused
case ended
}
/// The game length.
static let gameLength = 5
/// The interstitial ad.
var interstitial: GADInterstitialAd?
/// The countdown timer.
var timer: Timer?
/// The amount of time left in the game.
var timeLeft = gameLength
/// The state of the game.
var gameState = GameState.notStarted
/// The date that the timer was paused.
var pauseDate: Date?
/// The last fire date before a pause.
var previousFireDate: Date?
/// The countdown timer label.
@IBOutlet weak var gameText: UILabel!
/// The play again button.
@IBOutlet weak var playAgainButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Pause game when application enters background.
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.pauseGame),
name: UIApplication.didEnterBackgroundNotification, object: nil)
// Resume game when application becomes active.
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.resumeGame),
name: UIApplication.didBecomeActiveNotification, object: nil)
startNewGame()
}
// MARK: - Game Logic
fileprivate func startNewGame() {
loadInterstitial()
gameState = .playing
timeLeft = ViewController.gameLength
playAgainButton.isHidden = true
updateTimeLeft()
timer = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(ViewController.decrementTimeLeft(_:)),
userInfo: nil,
repeats: true)
}
fileprivate func loadInterstitial() {
let request = GADRequest()
GADInterstitialAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: request
) { (ad, error) in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
self.interstitial = ad
self.interstitial?.fullScreenContentDelegate = self
}
}
fileprivate func updateTimeLeft() {
gameText.text = "\(timeLeft) seconds left!"
}
@objc func decrementTimeLeft(_ timer: Timer) {
timeLeft -= 1
updateTimeLeft()
if timeLeft == 0 {
endGame()
}
}
@objc func pauseGame() {
if gameState != .playing {
return
}
gameState = .paused
// Record the relevant pause times.
pauseDate = Date()
previousFireDate = timer?.fireDate
// Prevent the timer from firing while app is in background.
timer?.fireDate = Date.distantFuture
}
@objc func resumeGame() {
if gameState != .paused {
return
}
gameState = .playing
// Calculate amount of time the app was paused.
let pauseTime = (pauseDate?.timeIntervalSinceNow)! * -1
// Set the timer to start firing again.
timer?.fireDate = (previousFireDate?.addingTimeInterval(pauseTime))!
}
fileprivate func endGame() {
gameState = .ended
timer?.invalidate()
timer = nil
let alert = UIAlertController(
title: "Game Over",
message: "You lasted \(ViewController.gameLength) seconds",
preferredStyle: .alert)
let alertAction = UIAlertAction(
title: "OK",
style: .cancel,
handler: { [weak self] action in
if let ad = self?.interstitial {
ad.present(fromRootViewController: self!)
} else {
print("Ad wasn't ready")
}
self?.playAgainButton.isHidden = false
})
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Interstitial Button Actions
@IBAction func playAgain(_ sender: AnyObject) {
startNewGame()
}
// MARK: - GADFullScreenContentDelegate
func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad will present full screen content.")
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error)
{
print("Ad failed to present full screen content with error \(error.localizedDescription).")
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad did dismiss full screen content.")
}
// MARK: - deinit
deinit {
NotificationCenter.default.removeObserver(
self,
name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.removeObserver(
self,
name: UIApplication.didBecomeActiveNotification, object: nil)
}
}
| apache-2.0 |
SuPair/edhita | Edhita/Models/SettingsForm.swift | 1 | 1704 | //
// SettingsForm.swift
// Edhita
//
// Created by Tatsuya Tobioka on 10/9/14.
// Copyright (c) 2014 tnantoka. All rights reserved.
//
import UIKit
public class SettingsForm: NSObject, FXForm {
private struct Defaults {
static let accessoryViewKey = "SettingsForm.Defaults.accessoryViewKey"
}
public class var sharedForm: SettingsForm {
struct Singleton {
static let sharedForm = SettingsForm()
}
return Singleton.sharedForm
}
override init() {
super.init()
var defaults = [String: AnyObject]()
defaults[Defaults.accessoryViewKey] = true
NSUserDefaults.standardUserDefaults().registerDefaults(defaults)
self.accessoryView = NSUserDefaults.standardUserDefaults().boolForKey(Defaults.accessoryViewKey)
}
var accessoryView: Bool = true {
didSet {
NSUserDefaults.standardUserDefaults().setBool(self.accessoryView, forKey: Defaults.accessoryViewKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
public func extraFields() -> [AnyObject]! {
return [
[
FXFormFieldHeader : "",
FXFormFieldType : FXFormFieldTypeLabel,
FXFormFieldAction : "fontDidTap:",
FXFormFieldTitle : NSLocalizedString("Font", comment: ""),
],
[
FXFormFieldHeader : "",
FXFormFieldType : FXFormFieldTypeLabel,
FXFormFieldAction : "acknowledgementsDidTap:",
FXFormFieldTitle : NSLocalizedString("Acknowledgements", comment: ""),
],
]
}
}
| mit |
vector-im/vector-ios | Riot/Modules/Spaces/SpaceMembers/MemberList/SpaceMemberListCoordinatorType.swift | 1 | 1350 | // File created from ScreenTemplate
// $ createScreen.sh Spaces/SpaceMembers/MemberList ShowSpaceMemberList
/*
Copyright 2021 New Vector Ltd
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
protocol SpaceMemberListCoordinatorDelegate: AnyObject {
func spaceMemberListCoordinator(_ coordinator: SpaceMemberListCoordinatorType, didSelect member: MXRoomMember, from sourceView: UIView?)
func spaceMemberListCoordinatorDidCancel(_ coordinator: SpaceMemberListCoordinatorType)
func spaceMemberListCoordinatorShowInvite(_ coordinator: SpaceMemberListCoordinatorType)
}
/// `SpaceMemberListCoordinatorType` is a protocol describing a Coordinator that handle key backup setup passphrase navigation flow.
protocol SpaceMemberListCoordinatorType: Coordinator, Presentable {
var delegate: SpaceMemberListCoordinatorDelegate? { get }
}
| apache-2.0 |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Home/ComposeToolbar.swift | 1 | 1463 | //
// ComposeToolbar.swift
// AYWeibo
//
// Created by Jinyong on 16/7/24.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class ComposeToolbar: UIToolbar {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// 接受外界传入的textView
var textView: UITextView?
/// 接受键盘视图
var keyboardView: UIView?
// MARK: - 内部控制方法
func setupUI() {
}
// 表情按钮
@IBAction func emotionBtnClick(sender: AnyObject) {
/*
通过观察发现,如果是系统默认的键盘inputView = nil
如果不是系统自带的键盘,那么inputView != nil
注意点:要切换键盘,必须先关闭键盘,切换之后再打开
*/
assert(textView != nil, "实现表情按钮textView不能为nil,需要外界传入textview")
// 1.先关闭键盘
textView?.resignFirstResponder()
// 2.判断inputView是否为nil,进行切换
if textView?.inputView != nil {
// 切换为系统键盘
textView?.inputView = nil
} else {
// 切换为自定义键盘
textView?.inputView = keyboardView
}
// 3.切换后打开键盘
textView?.becomeFirstResponder()
}
}
| apache-2.0 |
jay0420/jigsaw | JKPinTu-Swift/ViewControllers/Game2ViewController.swift | 2 | 352 | //
// Game2ViewController.swift
// JKPinTu-Swift
//
// Created by bingjie-macbookpro on 16/1/6.
// Copyright © 2016年 Bingjie. All rights reserved.
//
import UIKit
class Game2ViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| mit |
uasys/swift | test/SILGen/boxed_existentials.swift | 4 | 10806 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
func test_type_lowering(_ x: Error) { }
// CHECK-LABEL: sil hidden @_T018boxed_existentials18test_type_loweringys5Error_pF : $@convention(thin) (@owned Error) -> () {
// CHECK: destroy_value %0 : $Error
class Document {}
enum ClericalError: Error {
case MisplacedDocument(Document)
var _domain: String { return "" }
var _code: Int { return 0 }
}
func test_concrete_erasure(_ x: ClericalError) -> Error {
return x
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_concrete_erasures5Error_pAA08ClericalF0OF
// CHECK: bb0([[ARG:%.*]] : @owned $ClericalError):
// CHECK: [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError
// CHECK: [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[ADDR]] : $*ClericalError
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[EXISTENTIAL]] : $Error
protocol HairType {}
func test_composition_erasure(_ x: HairType & Error) -> Error {
return x
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials24test_composition_erasures5Error_psAC_AA8HairTypepF
// CHECK: [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*\) Error & HairType]]
// CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
// CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[ADDR]]
// CHECK: destroy_addr [[OLD_EXISTENTIAL]]
// CHECK: return [[NEW_EXISTENTIAL]]
protocol HairClass: class {}
func test_class_composition_erasure(_ x: HairClass & Error) -> Error {
return x
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials30test_class_composition_erasures5Error_psAC_AA9HairClasspF
// CHECK: [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*\) Error & HairClass]]
// CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
// CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
// CHECK: [[COPIED_VALUE:%.*]] = copy_value [[VALUE]]
// CHECK: store [[COPIED_VALUE]] to [init] [[ADDR]]
// CHECK: return [[NEW_EXISTENTIAL]]
func test_property(_ x: Error) -> String {
return x._domain
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials13test_propertySSs5Error_pF
// CHECK: bb0([[ARG:%.*]] : @owned $Error):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]]
// FIXME: Extraneous copy here
// CHECK-NEXT: [[COPY:%[0-9]+]] = alloc_stack $[[VALUE_TYPE]]
// CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[COPY]] : $*[[VALUE_TYPE]]
// CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1
// -- self parameter of witness is @in_guaranteed; no need to copy since
// value in box is immutable and box is guaranteed
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[RESULT]]
func test_property_of_lvalue(_ x: Error) -> String {
var x = x
return x._domain
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials23test_property_of_lvalueSSs5Error_pF :
// CHECK: bb0([[ARG:%.*]] : @owned $Error):
// CHECK: [[VAR:%.*]] = alloc_box ${ var Error }
// CHECK: [[PVAR:%.*]] = project_box [[VAR]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Error
// CHECK: store [[ARG_COPY]] to [init] [[PVAR]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PVAR]] : $*Error
// CHECK: [[VALUE_BOX:%.*]] = load [copy] [[ACCESS]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[VALUE_BOX]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[VALUE_TYPE]]
// CHECK: copy_addr [[VALUE]] to [initialization] [[COPY]]
// CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]])
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: destroy_value [[VALUE_BOX]]
// CHECK: destroy_value [[VAR]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '_T018boxed_existentials23test_property_of_lvalueSSs5Error_pF'
extension Error {
func extensionMethod() { }
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_extension_methodys5Error_pF
func test_extension_method(_ error: Error) {
// CHECK: bb0([[ARG:%.*]] : @owned $Error):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK-NOT: destroy_addr [[COPY]]
// CHECK-NOT: destroy_addr [[VALUE]]
// CHECK-NOT: destroy_addr [[VALUE]]
// -- destroy_value the owned argument
// CHECK: destroy_value %0
error.extensionMethod()
}
func plusOneError() -> Error { }
// CHECK-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsys5Error_p_sAC_ptF
// GUARANTEED-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsys5Error_p_sAC_ptF
// CHECK: bb0([[ARG0:%.*]]: @owned $Error,
// GUARANTEED: bb0([[ARG0:%.*]]: @owned $Error,
func test_open_existential_semantics(_ guaranteed: Error,
_ immediate: Error) {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// GUARANTEED: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// GUARANTEED: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// CHECK-NOT: copy_value [[ARG0]]
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG0]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-NOT: destroy_value [[ARG0]]
// GUARANTEED-NOT: copy_value [[ARG0]]
// GUARANTEED: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG0]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// GUARANTEED-NOT: destroy_value [[ARG0]]
guaranteed.extensionMethod()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error
// CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// -- need a copy_value to guarantee
// CHECK: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// -- end the guarantee
// -- TODO: could in theory do this sooner, after the value's been copied
// out.
// CHECK: destroy_value [[IMMEDIATE]]
// GUARANTEED: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error
// GUARANTEED: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// -- need a copy_value to guarantee
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// -- end the guarantee
// GUARANTEED: destroy_value [[IMMEDIATE]]
immediate.extensionMethod()
// CHECK: [[F:%.*]] = function_ref {{.*}}plusOneError
// CHECK: [[PLUS_ONE:%.*]] = apply [[F]]()
// CHECK: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_value [[PLUS_ONE]]
// GUARANTEED: [[F:%.*]] = function_ref {{.*}}plusOneError
// GUARANTEED: [[PLUS_ONE:%.*]] = apply [[F]]()
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// GUARANTEED: destroy_value [[PLUS_ONE]]
plusOneError().extensionMethod()
}
// CHECK-LABEL: sil hidden @_T018boxed_existentials14erasure_to_anyyps5Error_p_sAC_ptF
// CHECK: bb0([[OUT:%.*]] : @trivial $*Any, [[GUAR:%.*]] : @owned $Error,
func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
if true {
// CHECK-NOT: copy_value [[GUAR]]
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[GUAR:%.*]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK-NOT: destroy_value [[GUAR]]
return guaranteed
} else if true {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK: destroy_value [[IMMEDIATE]]
return immediate
} else if true {
// CHECK: function_ref boxed_existentials.plusOneError
// CHECK: [[PLUS_ONE:%.*]] = apply
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK: destroy_value [[PLUS_ONE]]
return plusOneError()
}
}
| apache-2.0 |
RobotRebels/SwiftLessons | chapter1/lesson1/11.05.2017.playground/Contents.swift | 1 | 688 | //: Playground - noun: a place where people can play
import Foundation
var peremennaia: Int = 1
//var имя_переменной = значение переменной
var myBirthday: Float
var testStr = "123"
var optionalNumber1: Int?
var optionalNumber3: Int?
optionalNumber3 = 5
//print(optionalNumber3)
//var optionalNumber2 = optionalNumber3!
//var number: Int = optionalNumber3 ?? 0
let number123: Int? = nil
print(number123)
func add(arg1: Double, arg2: Double) -> Double {
return arg1 + arg2
}
var value1: Float = 0.1
var value2 = 0.2
var result: Double
result = add(arg1: Double(value1), arg2: value2)
var a1: String = "123t"
var a2: Int = Int(a1) ?? 0
| mit |
StreamOneNL/iOS-SDK-ObjC | StreamOneSDKTests/SessionStoreTest.swift | 1 | 12153 | //
// File.swift
// StreamOneSDK
//
// Created by Nicky Gerritsen on 07-08-15.
// Copyright © 2015 StreamOne. All rights reserved.
//
import Quick
import Nimble
@testable import StreamOneSDK
protocol SessionStoreTest {
func constructSessionStore() -> SessionStore
}
extension SessionStoreTest {
func runTests() {
it("should not have a session by default") {
expect(self.constructSessionStore().hasSession).to(equal(false))
}
describe("when having an active session") {
var store: SessionStore!
beforeEach {
store = self.constructSessionStore()
store.setSession(id: "id", key: "key", userId: "user", timeout: 10)
}
it("should have a session") {
expect(store.hasSession).to(equal(true))
}
it("should not have a session after clearing it") {
store.clearSession()
expect(store.hasSession).to(equal(false))
}
it("should be able to retrieve the basic properties") {
self.testBasicProperties(id: "id", key: "key", userId: "user_id")
self.testBasicProperties(id: "7JhNCK-SWtEi'", key: "fAoMLYOCEpEi", userId: "_i5EDeMSEwIm")
}
it("should be able to set a cache key") {
let key = "thisisakey"
// Cache key should not be set
var error: NSError?
expect(store.hasCacheKey(key, error: &error)).to(equal(false))
expect(error).to(beNil())
error = nil
// Set the key and test that it succeeded
store.setCacheKey(key, value: "somerandomvalue", error: &error)
expect(error).to(beNil())
error = nil
// Cache key should not be set
expect(store.hasCacheKey(key, error: &error)).to(equal(true))
expect(error).to(beNil())
}
it("should be able to retrieve a set cache key") {
self.testSetGetCacheKey(store: store, key: "string", value: "string")
self.testSetGetCacheKey(store: store, key: "int", value: 27)
self.testSetGetCacheKey(store: store, key: "float", value: 3.14159)
self.testSetGetCacheKey(store: store, key: "bool-true", value: true)
self.testSetGetCacheKey(store: store, key: "bool-false", value: false)
self.testSetGetCacheKey(store: store, key: "array-empty", value: [])
self.testSetGetCacheKey(store: store, key: "array-values", value: [1, 2, 3])
self.testSetGetCacheKey(store: store, key: "dictionary", value: ["a": 5, "foo": "bar"])
}
it("should be able to unset a key") {
let key = "testUnsetCacheKey"
var error: NSError?
error = nil
store.setCacheKey(key, value: "some random value", error: &error)
expect(error).to(beNil())
error = nil
expect(store.hasCacheKey(key, error: &error)).to(equal(true))
expect(error).to(beNil())
error = nil
store.unsetCacheKey(key, error: &error)
expect(error).to(beNil())
error = nil
expect(store.hasCacheKey(key, error: &error)).to(equal(false))
expect(error).to(beNil())
}
it("should be able to clear the cache") {
let key = "testClearCacheKey"
var error: NSError?
error = nil
store.setCacheKey(key, value: "some random value", error: &error)
expect(error).to(beNil())
error = nil
expect(store.hasCacheKey(key, error: &error)).to(equal(true))
expect(error).to(beNil())
store.clearSession()
store.setSession(id: "id", key: "key", userId: "user", timeout: 10)
error = nil
expect(store.hasCacheKey(key, error: &error)).to(equal(false))
expect(error).to(beNil())
}
}
describe("error throwing") {
var store: SessionStore!
beforeEach {
store = self.constructSessionStore()
}
describe("without an active session") {
var error: NSError?
it("should throw a NoSession error when setting the timeout") {
error = nil
store.setTimeout(1234, error: &error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when requesting the id") {
error = nil
store.getId(&error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when requesting the key") {
error = nil
store.getKey(&error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when requesting the userId") {
error = nil
store.getUserId(&error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when requesting the timeout") {
error = nil
store.getTimeout(&error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when checking for a key") {
error = nil
store.hasCacheKey("abc", error: &error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when fetching a key") {
error = nil
store.getCacheKey("abc", error: &error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when setting a key") {
error = nil
store.setCacheKey("abc", value: "def", error: &error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
it("should throw a NoSession error when unsetting a key") {
error = nil
store.unsetCacheKey("abc", error: &error)
expect(error?.code).to(equal(SessionError.NoSession.rawValue))
}
}
describe("with an active session") {
var error: NSError?
beforeEach {
store.setSession(id: "a", key: "b", userId: "c", timeout: 1234)
}
it("should throw a NoSuchKey error when fetching a key") {
error = nil
store.getCacheKey("abc", error: &error)
expect(error?.code).to(equal(SessionError.NoSuchKey.rawValue))
}
it("should throw a NoSuchKey error when unsetting a key") {
error = nil
store.unsetCacheKey("abc", error: &error)
expect(error?.code).to(equal(SessionError.NoSuchKey.rawValue))
}
}
}
it("should have an initial timeout") {
// Use a fixed timeout
let timeout: NSTimeInterval = 10
// Store current time to obtain a bound on maximum timeout change
let startTime = NSDate().timeIntervalSince1970
// Construct store and set a session
let store = self.constructSessionStore()
store.setSession(id: "id", key: "key", userId: "user", timeout: timeout)
// Retrieve the stored timeout
var error: NSError?
let newTimeout = store.getTimeout(&error)
expect(error).to(beNil())
// Calculate maximum time passed
let timePassed = (NSDate().timeIntervalSince1970 - startTime)
// Check whether timeout decay is within margins
let timeoutDiff = timeout - newTimeout
expect(timeoutDiff).to(beLessThanOrEqualTo(timePassed))
}
it("should be possible to update the timeout") {
// Construct store and set a session with a low timeout
let store = self.constructSessionStore()
store.setSession(id: "id", key: "key", userId: "user", timeout: 5)
// Use a fixed timeout
let timeout: NSTimeInterval = 20
// Store current time to obtain a bound on maximum timeout change
let startTime = NSDate().timeIntervalSince1970
var error: NSError?
// Update timeout
store.setTimeout(timeout, error: &error)
expect(error).to(beNil())
error = nil
// Retrieve the stored timeout
let newTimeout = store.getTimeout(&error)
expect(error).to(beNil())
// Calculate maximum time passed
let timePassed = (NSDate().timeIntervalSince1970 - startTime)
// Check whether timeout decay is within margins
let timeoutDiff = timeout - newTimeout
expect(timeoutDiff).to(beLessThanOrEqualTo(timePassed))
}
it("should actually timeout after the given timeout") {
// Construct store and set a session with 0.3 second timeout
let store = self.constructSessionStore()
store.setSession(id: "id", key: "key", userId: "user", timeout: 0.3)
// There should be an active session
expect(store.hasSession).to(equal(true))
// The session should be inactive eventually, wait for at most 0.5 seconds
expect(store.hasSession).toEventually(equal(false), timeout: 0.5)
}
}
func testBasicProperties(id id: String, key: String, userId: String) {
let timeout: NSTimeInterval = 10
let store = constructSessionStore()
store.setSession(id: id, key: key, userId: userId, timeout: timeout)
expect(store.hasSession).to(equal(true))
var error: NSError?
error = nil
let idFromStore = store.getId(&error)
expect(error).to(beNil())
error = nil
let keyFromStore = store.getKey(&error)
expect(error).to(beNil())
error = nil
let userIdFromStore = store.getUserId(&error)
expect(error).to(beNil())
expect(idFromStore).to(equal(id))
expect(keyFromStore).to(equal(key))
expect(userIdFromStore).to(equal(userId))
}
func testSetGetCacheKey<T: Equatable>(store store: SessionStore, key: String, value: T) {
var error: NSError?
error = nil
store.setCacheKey(key, value: value as! AnyObject, error: &error)
expect(error).to(beNil())
error = nil
expect(store.hasCacheKey(key, error: &error)).to(equal(true))
expect(error).to(beNil())
error = nil
expect(store.getCacheKey(key, error: &error) as? T).to(equal(value))
expect(error).to(beNil())
}
} | mit |
zapdroid/RXWeather | Weather/Bookmark+CoreDataClass.swift | 1 | 236 | //
// Bookmark+CoreDataClass.swift
// RXWeather
//
// Created by Zafer Caliskan on 30/05/2017.
// Copyright © 2017 Boran ASLAN. All rights reserved.
//
import Foundation
import CoreData
public class Bookmark: NSManagedObject {
}
| mit |
mxcl/swift-package-manager | Sources/Basic/TerminalController.swift | 1 | 4354 | /*
This source file is part of the Swift.org open source project
Copyright 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 Swift project authors
*/
import libc
import func POSIX.getenv
/// A class to have better control on tty output streams: standard output and standard error.
/// Allows operations like cursor movement and colored text output on tty.
public final class TerminalController {
/// Terminal color choices.
public enum Color {
case noColor
case red
case green
case yellow
case cyan
case white
case black
case grey
/// Returns the color code which can be prefixed on a string to display it in that color.
fileprivate var string: String {
switch self {
case .noColor: return ""
case .red: return "\u{001B}[31m"
case .green: return "\u{001B}[32m"
case .yellow: return "\u{001B}[33m"
case .cyan: return "\u{001B}[36m"
case .white: return "\u{001B}[37m"
case .black: return "\u{001B}[30m"
case .grey: return "\u{001B}[30;1m"
}
}
}
/// Pointer to output stream to operate on.
private var stream: LocalFileOutputByteStream
/// Width of the terminal.
public let width: Int
/// Code to clear the line on a tty.
private let clearLineString = "\u{001B}[2K"
/// Code to end any currently active wrapping.
private let resetString = "\u{001B}[0m"
/// Code to make string bold.
private let boldString = "\u{001B}[1m"
/// Constructs the instance if the stream is a tty.
public init?(stream: LocalFileOutputByteStream) {
// Make sure this file stream is tty.
guard isatty(fileno(stream.fp)) != 0 else {
return nil
}
width = TerminalController.terminalWidth() ?? 80 // Assume default if we are not able to determine.
self.stream = stream
}
/// Tries to get the terminal width first using COLUMNS env variable and
/// if that fails ioctl method testing on stdout stream.
///
/// - Returns: Current width of terminal if it was determinable.
public static func terminalWidth() -> Int? {
// Try to get from enviornment.
if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) {
return width
}
// Try determining using ioctl.
var ws = winsize()
if ioctl(1, UInt(TIOCGWINSZ), &ws) == 0 {
return Int(ws.ws_col)
}
return nil
}
/// Flushes the stream.
public func flush() {
stream.flush()
}
/// Clears the current line and moves the cursor to beginning of the line..
public func clearLine() {
stream <<< clearLineString <<< "\r"
flush()
}
/// Moves the cursor y columns up.
public func moveCursor(y: Int) {
stream <<< "\u{001B}[\(y)A"
flush()
}
/// Writes a string to the stream.
public func write(_ string: String, inColor color: Color = .noColor, bold: Bool = false) {
writeWrapped(string, inColor: color, bold: bold, stream: stream)
flush()
}
/// Inserts a new line character into the stream.
public func endLine() {
stream <<< "\n"
flush()
}
/// Wraps the string into the color mentioned.
public func wrap(_ string: String, inColor color: Color, bold: Bool = false) -> String {
let stream = BufferedOutputByteStream()
writeWrapped(string, inColor: color, bold: bold, stream: stream)
guard let string = stream.bytes.asString else {
fatalError("Couldn't get string value from stream.")
}
return string
}
private func writeWrapped(_ string: String, inColor color: Color, bold: Bool = false, stream: OutputByteStream) {
// Don't wrap if string is empty or color is no color.
guard !string.isEmpty && color != .noColor else {
stream <<< string
return
}
stream <<< color.string <<< (bold ? boldString : "") <<< string <<< resetString
}
}
| apache-2.0 |
roambotics/swift | test/Concurrency/preconcurrency_typealias.swift | 2 | 1603 | // RUN: %target-swift-frontend -typecheck -verify %s
// REQUIRES: concurrency
@preconcurrency @MainActor func f() { }
// expected-note@-1 2{{calls to global function 'f()' from outside of its actor context are implicitly asynchronous}}
@preconcurrency typealias FN = @Sendable () -> Void
struct Outer {
@preconcurrency typealias FN = @Sendable () -> Void
}
@preconcurrency func preconcurrencyFunc(callback: FN) {}
func test() {
var _: Outer.FN = {
f()
}
var _: FN = {
f()
print("Hello")
}
var mutableVariable = 0
preconcurrencyFunc {
mutableVariable += 1 // no sendable warning
}
mutableVariable += 1
}
@available(SwiftStdlib 5.1, *)
func testAsync() async {
var _: Outer.FN = {
f() // expected-error{{call to main actor-isolated global function 'f()' in a synchronous nonisolated context}}
}
var _: FN = {
f() // expected-error{{call to main actor-isolated global function 'f()' in a synchronous nonisolated context}}
print("Hello")
}
var mutableVariable = 0
preconcurrencyFunc {
mutableVariable += 1 // expected-warning{{mutation of captured var 'mutableVariable' in concurrently-executing code; this is an error in Swift 6}}
}
mutableVariable += 1
}
// rdar://99518344 - @Sendable in nested positions
@preconcurrency typealias OtherHandler = @Sendable () -> Void
@preconcurrency typealias Handler = (@Sendable () -> OtherHandler?)?
@preconcurrency func f(arg: Int, withFn: Handler?) {}
class C {
func test() {
f(arg: 5, withFn: { [weak self] () -> OtherHandler? in
_ = self
return nil
})
}
}
| apache-2.0 |
roambotics/swift | test/stdlib/WeakMirror.swift | 2 | 9278 | //===--- Mirror.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: %empty-directory(%t)
//
// RUN: if [ %target-runtime == "objc" ]; \
// RUN: then \
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g && \
// RUN: %target-build-swift -Xfrontend -disable-access-control %s -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/Mirror; \
// RUN: else \
// RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Mirror; \
// RUN: fi
// RUN: %target-codesign %t/Mirror
// RUN: %target-run %t/Mirror
// REQUIRES: executable_test
// REQUIRES: shell
// REQUIRES: reflection
import StdlibUnittest
var mirrors = TestSuite("Mirrors")
class NativeSwiftClass : NativeClassBoundExistential {
let x: Int
init(x: Int) {
self.x = x
}
}
protocol NativeClassBoundExistential : AnyObject {
var x: Int { get }
}
class NativeSwiftClassHasWeak {
weak var weakProperty: AnyObject?
let x: Int
init(x: Int) {
self.x = x
}
}
class NativeSwiftClassHasNativeClassBoundExistential {
weak var weakProperty: NativeClassBoundExistential?
let x: Int
init(x: Int) {
self.x = x
}
}
struct StructHasNativeWeakReference {
weak var weakProperty: AnyObject?
let x: Int
init(x: Int) {
self.x = x
}
}
mirrors.test("class/NativeSwiftClassHasNativeWeakReference") {
let parent = NativeSwiftClassHasWeak(x: 1010)
let child = NativeSwiftClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/NativeSwiftClassHasNativeClassBoundExistential") {
let parent = NativeSwiftClassHasNativeClassBoundExistential(x: 1010)
let child = NativeSwiftClass(x: 2020) as NativeClassBoundExistential
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("struct/StructHasNativeWeakReference") {
var parent = StructHasNativeWeakReference(x: 1010)
let child = NativeSwiftClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
// https://github.com/apple/swift/issues/51384
// Using 'Mirror' to access a weak reference results in object being
// retained indefinitely
mirrors.test("class/NativeSwiftClassHasNativeWeakReferenceNoLeak") {
weak var verifier: AnyObject?
do {
let parent = NativeSwiftClassHasWeak(x: 1010)
let child = NativeSwiftClass(x: 2020)
verifier = child
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotNil(extractedChild)
expectNotNil(verifier)
// If child is destroyed, the above cast and checks will fail.
_fixLifetime(child)
}
expectNil(verifier)
}
#if _runtime(_ObjC)
import Foundation
@objc protocol ObjCClassExistential : AnyObject {
var weakProperty: AnyObject? { get set }
var x: Int { get }
}
class ObjCClass : ObjCClassExistential {
weak var weakProperty: AnyObject?
let x: Int
init(x: Int) {
self.x = x
}
}
class NativeSwiftClassHasObjCClassBoundExistential {
weak var weakProperty: ObjCClassExistential?
let x: Int
init(x: Int) {
self.x = x
}
}
class ObjCClassHasWeak : NSObject {
weak var weakProperty: AnyObject?
let x: Int
init(x: Int) {
self.x = x
}
}
class ObjCClassHasNativeClassBoundExistential : NSObject {
weak var weakProperty: NativeClassBoundExistential?
let x: Int
init(x: Int) {
self.x = x
}
}
class ObjCClassHasObjCClassBoundExistential : NSObject {
weak var weakProperty: ObjCClassExistential?
let x: Int
init(x: Int) {
self.x = x
}
}
struct StructHasObjCWeakReference {
weak var weakProperty: ObjCClass?
let x: Int
init(x: Int) {
self.x = x
}
}
struct StructHasObjCClassBoundExistential {
weak var weakProperty: ObjCClassExistential?
let x: Int
init(x: Int) {
self.x = x
}
}
mirrors.test("class/NativeSwiftClassHasObjCWeakReference") {
let parent = NativeSwiftClassHasWeak(x: 1010)
let child = ObjCClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/NativeSwiftClassHasObjCClassBoundExistential") {
let parent = NativeSwiftClassHasObjCClassBoundExistential(x: 1010)
let child = ObjCClass(x: 2020) as ObjCClassExistential
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/ObjCClassHasNativeWeak") {
let parent = ObjCClassHasWeak(x: 1010)
let child = NativeSwiftClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/ObjcCClassHasObjCWeakReference") {
let parent = ObjCClassHasWeak(x: 1010)
let child = ObjCClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/ObjCClassHasNativeClassBoundExistential") {
let parent = ObjCClassHasNativeClassBoundExistential(x: 1010)
let child = NativeSwiftClass(x: 2020) as NativeClassBoundExistential
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! NativeSwiftClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("class/ObjCClassHasObjCClassBoundExistential") {
let parent = ObjCClassHasObjCClassBoundExistential(x: 1010)
let child = ObjCClass(x: 2020) as ObjCClassExistential
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("struct/StructHasObjCWeakReference") {
var parent = StructHasObjCWeakReference(x: 1010)
let child = ObjCClass(x: 2020)
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
mirrors.test("struct/StructHasObjCClassBoundExistential") {
var parent = StructHasObjCClassBoundExistential(x: 1010)
let child = ObjCClass(x: 2020) as ObjCClassExistential
parent.weakProperty = child
let mirror = Mirror(reflecting: parent)
let children = Array(mirror.children)
let extractedChild = children[0].1 as! ObjCClass
expectNotEqual(parent.x, extractedChild.x)
expectEqual(ObjectIdentifier(child), ObjectIdentifier(extractedChild))
expectEqual(child.x, extractedChild.x)
print(extractedChild)
}
#endif
runAllTests()
| apache-2.0 |
RadioBear/CalmKit | CalmKit/Animators/BRBCalmKitCircleFlipAnimator.swift | 1 | 2748 | //
// BRBCalmKitCircleFlipAnimator.swift
// CalmKit
//
// Copyright (c) 2016 RadioBear
//
// 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
class BRBCalmKitCircleFlipAnimator: BRBCalmKitAnimator {
func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) {
let circle = CALayer()
circle.frame = CGRectInset(CGRectMake(0.0, 0.0, size.width, size.height), 2.0, 2.0)
circle.backgroundColor = color.CGColor
circle.cornerRadius = circle.bounds.height * 0.5
circle.anchorPoint = CGPointMake(0.5, 0.5)
circle.anchorPointZ = 0.5
circle.shouldRasterize = true
circle.rasterizationScale = UIScreen.mainScreen().scale
layer.addSublayer(circle)
let anim = CAKeyframeAnimation(keyPath: "transform")
anim.removedOnCompletion = false
anim.repeatCount = HUGE
anim.duration = 1.2
anim.keyTimes = [0.0, 0.5, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
]
anim.values = [
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, 0, 0, 0, 0)),
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, CGFloat(M_PI), 0.0, 1.0, 0.0)),
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, CGFloat(M_PI), 0.0, 0.0, 1.0)),
]
circle.addAnimation(anim, forKey:"calmkit-anim")
}
}
| mit |
atomkirk/TouchForms | TouchForms/Source/FormTextField.swift | 1 | 600 | //
// FormTextField.swift
// TouchForms
//
// Created by Adam Kirk on 7/25/15.
// Copyright (c) 2015 Adam Kirk. All rights reserved.
//
import UIKit
@IBDesignable
class FormTextField: UITextField {
@IBInspectable var inset: CGFloat = 5
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds, inset, 0)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
}
| mit |
material-components/material-components-ios-codelabs | MDC-103/Swift/Starter/Shrine/Shrine/CustomLayout.swift | 4 | 5364 | /*
Copyright 2018-present the Material Components for iOS 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.
*/
import UIKit
private let HORIZONTAL_PADDING: CGFloat = 0.10
class CustomLayout: UICollectionViewLayout {
var itemASize: CGSize = .zero
var itemBSize: CGSize = .zero
var itemCSize: CGSize = .zero
var itemAOffset: CGPoint = .zero
var itemBOffset: CGPoint = .zero
var itemCOffset: CGPoint = .zero
var tripleSize: CGSize = .zero
var frameCache = [NSValue]()
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepare() {
super.prepare()
var parentFrame = self.collectionView!.bounds.standardized
parentFrame = UIEdgeInsetsInsetRect(parentFrame, self.collectionView!.adjustedContentInset)
let contentHeight = parentFrame.size.height -
(self.collectionView!.contentInset.top + self.collectionView!.contentInset.bottom)
let contentWidth = parentFrame.size.width
let landscapeItemSize = CGSize(width: contentWidth * 0.46, height: contentHeight * 0.32)
let portaitItemSize = CGSize(width: contentWidth * 0.3, height: contentHeight * 0.54)
self.itemASize = landscapeItemSize
self.itemBSize = landscapeItemSize
self.itemCSize = portaitItemSize
self.itemAOffset = CGPoint(x: contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.66)
self.itemBOffset = CGPoint(x: contentWidth * 0.3, y: contentHeight * 0.16)
self.itemCOffset = CGPoint(x: self.itemBOffset.x + self.itemBSize.width + contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.2)
self.tripleSize = CGSize(width: self.itemCOffset.x + self.itemCSize.width, height: contentHeight)
self.frameCache.removeAll()
for itemIndex in 0..<self.collectionView!.numberOfItems(inSection:0) {
let tripleCount = itemIndex / 3
let internalIndex = itemIndex % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let frameValue: NSValue = NSValue(cgRect: itemFrame)
self.frameCache.append(frameValue)
}
}
override var collectionViewContentSize: CGSize {
get {
var contentSize: CGSize = .zero
contentSize.height = self.tripleSize.height
let lastItemFrameValue: NSValue = self.frameCache.last!
let lastItemFrame = lastItemFrameValue.cgRectValue
contentSize.width = lastItemFrame.maxX + HORIZONTAL_PADDING * self.collectionView!.frame.width
return contentSize
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
for itemIndex in 0..<self.frameCache.count {
let itemFrame = self.frameCache[itemIndex].cgRectValue
if rect.intersects(itemFrame) {
let indexPath = IndexPath(row: itemIndex, section: 0)
let attributes = self.collectionView!.layoutAttributesForItem(at: indexPath)!
attributes.frame = itemFrame
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let tripleCount = indexPath.row / 3
let internalIndex = indexPath.row % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let attributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attributes.frame = itemFrame
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| apache-2.0 |
hxx0215/VPNOn | VPNOn/LTVPNAboutViewController.swift | 1 | 516 | //
// LTVPNAboutViewController.swift
// VPNOn
//
// Created by Lex Tang on 1/6/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
class LTVPNAboutViewController : UIViewController {
@IBOutlet weak var versionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String? {
versionLabel.text = version
}
}
}
| mit |
sgr-ksmt/PullToDismiss | Sources/PullToDismiss.swift | 1 | 9349 | //
// PullToDismiss.swift
// PullToDismiss
//
// Created by Suguru Kishimoto on 11/13/16.
// Copyright © 2016 Suguru Kishimoto. All rights reserved.
//
import Foundation
import UIKit
open class PullToDismiss: NSObject {
public struct Defaults {
private init() {}
public static let dismissableHeightPercentage: CGFloat = 0.33
}
open var backgroundEffect: BackgroundEffect? = ShadowEffect.default
open var edgeShadow: EdgeShadow? = EdgeShadow.default
public var dismissAction: (() -> Void)?
public weak var delegate: UIScrollViewDelegate? {
didSet {
var delegates: [UIScrollViewDelegate] = [self]
if let delegate = delegate {
delegates.append(delegate)
}
proxy = ScrollViewDelegateProxy(delegates: delegates)
}
}
public var dismissableHeightPercentage: CGFloat = Defaults.dismissableHeightPercentage {
didSet {
dismissableHeightPercentage = min(max(0.0, dismissableHeightPercentage), 1.0)
}
}
fileprivate var viewPositionY: CGFloat = 0.0
fileprivate var dragging: Bool = false
fileprivate var previousContentOffsetY: CGFloat = 0.0
fileprivate weak var viewController: UIViewController?
private var __scrollView: UIScrollView?
private var proxy: ScrollViewDelegateProxy? {
didSet {
__scrollView?.delegate = proxy
}
}
private var panGesture: UIPanGestureRecognizer?
private var backgroundView: UIView?
private var navigationBarHeight: CGFloat = 0.0
private var blurSaturationDeltaFactor: CGFloat = 1.8
convenience public init?(scrollView: UIScrollView) {
guard let viewController = type(of: self).viewControllerFromScrollView(scrollView) else {
print("a scrollView must be on the view controller.")
return nil
}
self.init(scrollView: scrollView, viewController: viewController)
}
public init(scrollView: UIScrollView, viewController: UIViewController, navigationBar: UIView? = nil) {
super.init()
self.proxy = ScrollViewDelegateProxy(delegates: [self])
self.__scrollView = scrollView
self.__scrollView?.delegate = self.proxy
self.viewController = viewController
if let navigationBar = navigationBar ?? viewController.navigationController?.navigationBar {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
navigationBar.addGestureRecognizer(gesture)
self.navigationBarHeight = navigationBar.frame.height
self.panGesture = gesture
}
}
deinit {
if let panGesture = panGesture {
panGesture.view?.removeGestureRecognizer(panGesture)
}
proxy = nil
__scrollView?.delegate = nil
__scrollView = nil
}
fileprivate var targetViewController: UIViewController? {
return viewController?.navigationController ?? viewController
}
private var haveShadowEffect: Bool {
return backgroundEffect != nil || edgeShadow != nil
}
fileprivate func dismiss() {
targetViewController?.dismiss(animated: true, completion: nil)
}
// MARK: - shadow view
private func makeBackgroundView() {
deleteBackgroundView()
guard let backgroundEffect = backgroundEffect else {
return
}
let backgroundView = backgroundEffect.makeBackgroundView()
backgroundView.frame = targetViewController?.view.bounds ?? .zero
switch backgroundEffect.target {
case .targetViewController:
targetViewController?.view.addSubview(backgroundView)
backgroundView.superview?.sendSubviewToBack(backgroundView)
backgroundView.frame = targetViewController?.view.bounds ?? .zero
case .presentingViewController:
targetViewController?.presentingViewController?.view.addSubview(backgroundView)
backgroundView.frame = targetViewController?.presentingViewController?.view.bounds ?? .zero
}
self.backgroundView = backgroundView
}
private func updateBackgroundView(rate: CGFloat) {
guard let backgroundEffect = backgroundEffect else {
return
}
backgroundEffect.applyEffect(view: backgroundView, rate: rate)
}
private func deleteBackgroundView() {
backgroundView?.removeFromSuperview()
backgroundView = nil
targetViewController?.view.clipsToBounds = true
}
private func resetBackgroundView() {
guard let backgroundEffect = backgroundEffect else {
return
}
backgroundEffect.applyEffect(view: backgroundView, rate: 1.0)
}
@objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .began:
startDragging()
case .changed:
let diff = gesture.translation(in: gesture.view).y
updateViewPosition(offset: diff)
gesture.setTranslation(.zero, in: gesture.view)
case .ended:
finishDragging(withVelocity: .zero)
default:
break
}
}
fileprivate func startDragging() {
targetViewController?.view.layer.removeAllAnimations()
backgroundView?.layer.removeAllAnimations()
viewPositionY = 0.0
makeBackgroundView()
targetViewController?.view.applyEdgeShadow(edgeShadow)
if haveShadowEffect {
targetViewController?.view.clipsToBounds = false
}
}
fileprivate func updateViewPosition(offset: CGFloat) {
var addOffset: CGFloat = offset
// avoid statusbar gone
if viewPositionY >= 0 && viewPositionY < 0.05 {
addOffset = min(max(-0.01, addOffset), 0.01)
}
viewPositionY += addOffset
targetViewController?.view.frame.origin.y = max(0.0, viewPositionY)
if case .some(.targetViewController) = backgroundEffect?.target {
backgroundView?.frame.origin.y = -(targetViewController?.view.frame.origin.y ?? 0.0)
}
let targetViewOriginY: CGFloat = targetViewController?.view.frame.origin.y ?? 0.0
let targetViewHeight: CGFloat = targetViewController?.view.frame.height ?? 0.0
let rate: CGFloat = (1.0 - (targetViewOriginY / (targetViewHeight * dismissableHeightPercentage)))
updateBackgroundView(rate: rate)
targetViewController?.view.updateEdgeShadow(edgeShadow, rate: rate)
}
fileprivate func finishDragging(withVelocity velocity: CGPoint) {
let originY = targetViewController?.view.frame.origin.y ?? 0.0
let dismissableHeight = (targetViewController?.view.frame.height ?? 0.0) * dismissableHeightPercentage
if originY > dismissableHeight || originY > 0 && velocity.y < 0 {
deleteBackgroundView()
targetViewController?.view.detachEdgeShadow()
proxy = nil
_ = dismissAction?() ?? dismiss()
} else if originY != 0.0 {
UIView.perform(.delete, on: [], options: [.allowUserInteraction], animations: { [weak self] in
self?.targetViewController?.view.frame.origin.y = 0.0
self?.resetBackgroundView()
self?.targetViewController?.view.updateEdgeShadow(self?.edgeShadow, rate: 1.0)
}) { [weak self] finished in
if finished {
self?.deleteBackgroundView()
self?.targetViewController?.view.detachEdgeShadow()
}
}
} else {
self.deleteBackgroundView()
}
viewPositionY = 0.0
}
private static func viewControllerFromScrollView(_ scrollView: UIScrollView) -> UIViewController? {
var responder: UIResponder? = scrollView
while let r = responder {
if let viewController = r as? UIViewController {
return viewController
}
responder = r.next
}
return nil
}
}
extension PullToDismiss: UITableViewDelegate {
}
extension PullToDismiss: UICollectionViewDelegate {
}
extension PullToDismiss: UICollectionViewDelegateFlowLayout {
}
extension PullToDismiss: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if dragging {
let diff = -(scrollView.contentOffset.y - previousContentOffsetY)
if scrollView.contentOffset.y < -scrollView.contentInset.top || (targetViewController?.view.frame.origin.y ?? 0.0) > 0.0 {
updateViewPosition(offset: diff)
scrollView.contentOffset.y = -scrollView.contentInset.top
}
previousContentOffsetY = scrollView.contentOffset.y
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startDragging()
dragging = true
previousContentOffsetY = scrollView.contentOffset.y
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
finishDragging(withVelocity: velocity)
dragging = false
previousContentOffsetY = 0.0
}
}
| mit |
SvenTiigi/STLocationRequest | Sources/Authorization/STLocationRequestController+Authorization.swift | 1 | 599 | //
// STLocationRequestController+Authorization.swift
// STLocationRequest
//
// Created by Sven Tiigi on 18.11.17.
//
import Foundation
// MARK: - Authorization
public extension STLocationRequestController {
/// Enum to decide which location request type should be used
enum Authorization: String, Codable, Equatable, Hashable, CaseIterable {
/// Location-Request when in use authorization
case requestWhenInUseAuthorization
#if os(iOS)
/// Location-Request always authorization
case requestAlwaysAuthorization
#endif
}
}
| mit |
LamineNdy/SampleApp | SampleApp/Classes/Services/ResponseSerializer.swift | 1 | 2955 | //
// ResponseSerializer.swift
// Pods
//
// Created by Lamine NDIAYE on 30/11/16.
//
//
import Foundation
import Alamofire
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
public protocol ResponseObjectSerializable {
init?(response: HTTPURLResponse, representation: AnyObject)
}
extension DataRequest {
func responseObject<T: ResponseObjectSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<T>) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response, let responseObject = T(response: response, representation: jsonObject as AnyObject) else {
return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)"))
}
return .success(responseObject)
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
protocol ResponseCollectionSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self]
}
extension DataRequest {
@discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self
{
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
| mit |
Xiaolong-Jin/Aerodramus | Aerodramus/Aerodramus/Promise/Extensions/UIKit/UIActivityIndicatorView/UIActivityIndicatorView+Promise.swift | 1 | 415 | //
// UIActivityIndicatorView+Promise.swift
// Aerodramus
//
// Created by 金晓龙 on 2017/7/30.
// Copyright © 2017年 Zodiac.com. All rights reserved.
//
import UIKit.UIActivityIndicatorView
public extension UIActivityIndicatorView {
public func prms_bind<T>(with promise: Promise<T>) {
self.startAnimating()
promise.always({ [weak self] _,_ in self?.stopAnimating() })
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/01060-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 1580 | // 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
// RUN: not %target-swift-frontend %s -parse
class a {
type b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
protocol A {
}
struct B : A {
}
struct C<D, E: A where D.C == E> {
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
class A: A {
}
class B : C {
}
typealias C = B
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
return x
}
}
return nil
}
let xs : [Int?] = [nil, 4, nil]
print(some(xs))
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
| apache-2.0 |
kstaring/swift | test/Serialization/target-incompatible.swift | 4 | 1199 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %swift -target x86_64-unknown-darwin14 -o %t/mips-template.swiftmodule -parse-stdlib -emit-module -module-name mips %S/../Inputs/empty.swift
// RUN: %S/Inputs/binary_sub.py x86_64-unknown-darwin14 mips64-unknown-darwin14 < %t/mips-template.swiftmodule > %t/mips.swiftmodule
// RUN: not %target-swift-frontend -I %t -parse -parse-stdlib %s -DMIPS 2>&1 | %FileCheck -check-prefix=CHECK-MIPS %s
// RUN: %swift -target x86_64-unknown-darwin14 -o %t/solaris-template.swiftmodule -parse-stdlib -emit-module -module-name solaris %S/../Inputs/empty.swift
// RUN: %S/Inputs/binary_sub.py x86_64-unknown-darwin14 x86_64-unknown-solaris8 < %t/solaris-template.swiftmodule > %t/solaris.swiftmodule
// RUN: not %target-swift-frontend -I %t -parse -parse-stdlib %s -DSOLARIS 2>&1 | %FileCheck -check-prefix=CHECK-SOLARIS %s
#if MIPS
// CHECK-MIPS: :[[@LINE+1]]:8: error: module file was created for incompatible target mips64-unknown-darwin14: {{.*}}mips.swiftmodule{{$}}
import mips
#elseif SOLARIS
// CHECK-SOLARIS: :[[@LINE+1]]:8: error: module file was created for incompatible target x86_64-unknown-solaris8: {{.*}}solaris.swiftmodule{{$}}
import solaris
#endif
| apache-2.0 |
fgengine/quickly | Quickly/Views/Fields/MultiText/QMultiTextField.swift | 1 | 23511 | //
// Quickly
//
public protocol IQMultiTextFieldObserver : class {
func beginEditing(multiTextField: QMultiTextField)
func editing(multiTextField: QMultiTextField)
func endEditing(multiTextField: QMultiTextField)
func pressed(multiTextField: QMultiTextField, action: QFieldAction)
func changed(multiTextField: QMultiTextField, height: CGFloat)
}
open class QMultiTextFieldStyleSheet : QDisplayStyleSheet {
public var validator: IQStringValidator?
public var form: IQFieldForm?
public var textInsets: UIEdgeInsets
public var textStyle: IQTextStyle?
public var placeholderInsets: UIEdgeInsets
public var placeholder: IQText?
public var maximumNumberOfCharecters: UInt
public var maximumNumberOfLines: UInt
public var minimumHeight: CGFloat
public var maximumHeight: CGFloat
public var autocapitalizationType: UITextAutocapitalizationType
public var autocorrectionType: UITextAutocorrectionType
public var spellCheckingType: UITextSpellCheckingType
public var keyboardType: UIKeyboardType
public var keyboardAppearance: UIKeyboardAppearance
public var returnKeyType: UIReturnKeyType
public var enablesReturnKeyAutomatically: Bool
public var isSecureTextEntry: Bool
public var textContentType: UITextContentType!
public var isEnabled: Bool
public var toolbarStyle: QToolbarStyleSheet?
public var toolbarActions: QFieldAction
public init(
validator: IQStringValidator? = nil,
form: IQFieldForm? = nil,
textInsets: UIEdgeInsets = UIEdgeInsets.zero,
textStyle: IQTextStyle? = nil,
placeholderInsets: UIEdgeInsets = UIEdgeInsets.zero,
placeholder: IQText? = nil,
maximumNumberOfCharecters: UInt = 0,
maximumNumberOfLines: UInt = 0,
minimumHeight: CGFloat = 0,
maximumHeight: CGFloat = 0,
autocapitalizationType: UITextAutocapitalizationType = .none,
autocorrectionType: UITextAutocorrectionType = .default,
spellCheckingType: UITextSpellCheckingType = .default,
keyboardType: UIKeyboardType = .default,
keyboardAppearance: UIKeyboardAppearance = .default,
returnKeyType: UIReturnKeyType = .default,
enablesReturnKeyAutomatically: Bool = true,
isSecureTextEntry: Bool = false,
textContentType: UITextContentType! = nil,
isEnabled: Bool = true,
toolbarStyle: QToolbarStyleSheet? = nil,
toolbarActions: QFieldAction = [ .done ],
backgroundColor: UIColor? = nil,
tintColor: UIColor? = nil,
cornerRadius: QViewCornerRadius = .none,
border: QViewBorder = .none,
shadow: QViewShadow? = nil
) {
self.validator = validator
self.form = form
self.textInsets = textInsets
self.textStyle = textStyle
self.placeholderInsets = placeholderInsets
self.placeholder = placeholder
self.maximumNumberOfCharecters = maximumNumberOfCharecters
self.maximumNumberOfLines = maximumNumberOfLines
self.minimumHeight = minimumHeight
self.maximumHeight = maximumHeight
self.autocapitalizationType = autocapitalizationType
self.autocorrectionType = autocorrectionType
self.spellCheckingType = spellCheckingType
self.keyboardType = keyboardType
self.keyboardAppearance = keyboardAppearance
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
self.isSecureTextEntry = isSecureTextEntry
self.textContentType = textContentType
self.isEnabled = isEnabled
self.toolbarStyle = toolbarStyle
self.toolbarActions = toolbarActions
super.init(
backgroundColor: backgroundColor,
tintColor: tintColor,
cornerRadius: cornerRadius,
border: border,
shadow: shadow
)
}
public init(_ styleSheet: QMultiTextFieldStyleSheet) {
self.validator = styleSheet.validator
self.form = styleSheet.form
self.textInsets = styleSheet.textInsets
self.textStyle = styleSheet.textStyle
self.placeholderInsets = styleSheet.placeholderInsets
self.placeholder = styleSheet.placeholder
self.maximumNumberOfCharecters = styleSheet.maximumNumberOfCharecters
self.maximumNumberOfLines = styleSheet.maximumNumberOfLines
self.minimumHeight = styleSheet.minimumHeight
self.maximumHeight = styleSheet.maximumHeight
self.autocapitalizationType = styleSheet.autocapitalizationType
self.autocorrectionType = styleSheet.autocorrectionType
self.spellCheckingType = styleSheet.spellCheckingType
self.keyboardType = styleSheet.keyboardType
self.keyboardAppearance = styleSheet.keyboardAppearance
self.returnKeyType = styleSheet.returnKeyType
self.enablesReturnKeyAutomatically = styleSheet.enablesReturnKeyAutomatically
self.isSecureTextEntry = styleSheet.isSecureTextEntry
self.textContentType = styleSheet.textContentType
self.isEnabled = styleSheet.isEnabled
self.toolbarStyle = styleSheet.toolbarStyle
self.toolbarActions = styleSheet.toolbarActions
super.init(styleSheet)
}
}
public class QMultiTextField : QDisplayView, IQField {
public typealias ShouldClosure = (_ multiTextField: QMultiTextField) -> Bool
public typealias ActionClosure = (_ multiTextField: QMultiTextField, _ action: QFieldAction) -> Void
public typealias Closure = (_ multiTextField: QMultiTextField) -> Void
public var validator: IQStringValidator? {
willSet { self._field.delegate = nil }
didSet {self._field.delegate = self._fieldDelegate }
}
public var form: IQFieldForm? {
didSet(oldValue) {
if self.form !== oldValue {
if let form = oldValue {
form.remove(field: self)
}
if let form = self.form {
form.add(field: self)
}
}
}
}
public var textStyle: IQTextStyle? {
didSet {
self._field.font = self.textStyle?.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
self._field.textColor = self.textStyle?.color ?? UIColor.black
self._field.textAlignment = self.textStyle?.alignment ?? .left
self.textHeight = self._textHeight()
}
}
public var textInsets: UIEdgeInsets {
set(value) {
if self._field.textContainerInset != value {
self._field.textContainerInset = value
self.textHeight = self._textHeight()
}
}
get { return self._field.textContainerInset }
}
public var text: String {
set(value) {
if self._field.text != value {
self._field.text = value
self._updatePlaceholderVisibility()
self.textHeight = self._textHeight()
if let form = self.form {
form.validation()
}
}
}
get { return self._field.text }
}
public var unformatText: String {
set(value) {
self._field.text = value
self._updatePlaceholderVisibility()
self.textHeight = self._textHeight()
if let form = self.form {
form.validation()
}
}
get {
if let text = self._field.text {
return text
}
return ""
}
}
public var placeholderInsets: UIEdgeInsets = UIEdgeInsets.zero {
didSet(oldValue) {
if self.placeholderInsets != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var selectedRange: NSRange {
set(value) { self._field.selectedRange = value }
get { return self._field.selectedRange }
}
public var maximumNumberOfCharecters: UInt = 0
public var maximumNumberOfLines: UInt = 0
public var minimumHeight: CGFloat = 0 {
didSet(oldValue) {
if self.minimumHeight != oldValue {
self.textHeight = self._textHeight()
}
}
}
public var maximumHeight: CGFloat = 0 {
didSet(oldValue) {
if self.maximumHeight != oldValue {
self.textHeight = self._textHeight()
}
}
}
public private(set) var textHeight: CGFloat = 0
public var isValid: Bool {
get {
guard let validator = self.validator else { return true }
return validator.validate(self.unformatText).isValid
}
}
public var placeholder: IQText? {
set(value) {
self._placeholderLabel.text = value
self._updatePlaceholderVisibility()
}
get { return self._placeholderLabel.text }
}
public var isEditable: Bool {
set(value) { self._field.isEditable = value }
get { return self._field.isEditable }
}
public var isSelectable: Bool {
set(value) { self._field.isSelectable = value }
get { return self._field.isSelectable }
}
public var isEnabled: Bool {
set(value) { self._field.isUserInteractionEnabled = value }
get { return self._field.isUserInteractionEnabled }
}
public var isEditing: Bool {
get { return self._field.isFirstResponder }
}
public lazy var toolbar: QToolbar = {
let items = self._toolbarItems()
let view = QToolbar(items: items)
view.isHidden = items.isEmpty
return view
}()
public var toolbarActions: QFieldAction = [] {
didSet(oldValue) {
if self.toolbarActions != oldValue {
let items = self._toolbarItems()
self.toolbar.items = items
self.toolbar.isHidden = items.isEmpty
self.reloadInputViews()
}
}
}
public var onShouldBeginEditing: ShouldClosure?
public var onBeginEditing: Closure?
public var onEditing: Closure?
public var onShouldEndEditing: ShouldClosure?
public var onEndEditing: Closure?
public var onPressedAction: ActionClosure?
public var onChangedHeight: Closure?
private var _placeholderLabel: QLabel!
private var _field: Field!
private var _fieldDelegate: FieldDelegate!
private var _observer: QObserver< IQMultiTextFieldObserver > = QObserver< IQMultiTextFieldObserver >()
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.removeConstraints(self._constraints) }
didSet { self.addConstraints(self._constraints) }
}
open override func setup() {
super.setup()
self.backgroundColor = UIColor.clear
self._fieldDelegate = FieldDelegate(field: self)
self._placeholderLabel = QLabel(frame: self.bounds.inset(by: self.placeholderInsets))
self._placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self._placeholderLabel)
self._field = Field(frame: self.bounds)
self._field.translatesAutoresizingMaskIntoConstraints = false
self._field.textContainer.lineFragmentPadding = 0
self._field.layoutManager.usesFontLeading = false
self._field.inputAccessoryView = self.toolbar
self._field.delegate = self._fieldDelegate
self.insertSubview(self._field, aboveSubview: self._placeholderLabel)
self.textHeight = self._textHeight()
}
open override func updateConstraints() {
super.updateConstraints()
self._constraints = [
self._placeholderLabel.topLayout == self.topLayout.offset(self.placeholderInsets.top),
self._placeholderLabel.leadingLayout == self.leadingLayout.offset(self.placeholderInsets.left),
self._placeholderLabel.trailingLayout == self.trailingLayout.offset(-self.placeholderInsets.right),
self._placeholderLabel.bottomLayout == self.bottomLayout.offset(-self.placeholderInsets.bottom),
self._field.topLayout == self.topLayout,
self._field.leadingLayout == self.leadingLayout,
self._field.trailingLayout == self.trailingLayout,
self._field.bottomLayout == self.bottomLayout
]
}
public func add(observer: IQMultiTextFieldObserver, priority: UInt) {
self._observer.add(observer, priority: priority)
}
public func remove(observer: IQMultiTextFieldObserver) {
self._observer.remove(observer)
}
open func beginEditing() {
self._field.becomeFirstResponder()
}
public func apply(_ styleSheet: QMultiTextFieldStyleSheet) {
self.apply(styleSheet as QDisplayStyleSheet)
self.validator = styleSheet.validator
self.form = styleSheet.form
self.textInsets = styleSheet.textInsets
self.textStyle = styleSheet.textStyle
self.placeholderInsets = styleSheet.placeholderInsets
self.placeholder = styleSheet.placeholder
self.maximumNumberOfCharecters = styleSheet.maximumNumberOfCharecters
self.maximumNumberOfLines = styleSheet.maximumNumberOfLines
self.minimumHeight = styleSheet.minimumHeight
self.maximumHeight = styleSheet.maximumHeight
self.autocapitalizationType = styleSheet.autocapitalizationType
self.autocorrectionType = styleSheet.autocorrectionType
self.spellCheckingType = styleSheet.spellCheckingType
self.keyboardType = styleSheet.keyboardType
self.keyboardAppearance = styleSheet.keyboardAppearance
self.returnKeyType = styleSheet.returnKeyType
self.enablesReturnKeyAutomatically = styleSheet.enablesReturnKeyAutomatically
self.isSecureTextEntry = styleSheet.isSecureTextEntry
if #available(iOS 10.0, *) {
self.textContentType = styleSheet.textContentType
}
self.isEnabled = styleSheet.isEnabled
if let style = styleSheet.toolbarStyle {
self.toolbar.apply(style)
}
self.toolbarActions = styleSheet.toolbarActions
}
}
// MARK: Private
private extension QMultiTextField {
func _updatePlaceholderVisibility() {
self._placeholderLabel.isHidden = self._field.text.count > 0
}
func _textHeight() -> CGFloat {
let textContainerInset = self._field.textContainerInset
let textRect = self._field.layoutManager.usedRect(for: self._field.textContainer)
var height = textContainerInset.top + textRect.height + textContainerInset.bottom
if self.minimumHeight > CGFloat.leastNonzeroMagnitude {
height = max(height, self.minimumHeight)
}
if self.maximumHeight > CGFloat.leastNonzeroMagnitude {
height = min(height, self.maximumHeight)
}
return height
}
private func _toolbarItems() -> [UIBarButtonItem] {
var items: [UIBarButtonItem] = []
if self.toolbarActions.isEmpty == false {
if self.toolbarActions.contains(.cancel) == true {
items.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self._pressedCancel(_:))))
}
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))
if self.toolbarActions.contains(.done) == true {
items.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self._pressedDone(_:))))
}
}
return items
}
@objc
func _pressedCancel(_ sender: Any) {
self._pressed(action: .cancel)
self.endEditing(false)
}
@objc
func _pressedDone(_ sender: Any) {
self._pressed(action: .done)
self.endEditing(false)
}
func _pressed(action: QFieldAction) {
if let closure = self.onPressedAction {
closure(self, action)
}
self._observer.notify({ (observer) in
observer.pressed(multiTextField: self, action: action)
})
}
}
// MARK: Private • Field
private extension QMultiTextField {
class Field : UITextView, IQView {
public override var inputAccessoryView: UIView? {
set(value) { super.inputAccessoryView = value }
get {
guard let view = super.inputAccessoryView else { return nil }
return view.isHidden == true ? nil : view
}
}
required init() {
super.init(
frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40),
textContainer: nil
)
self.setup()
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(
frame: frame,
textContainer: nil
)
self.setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setup()
}
open func setup() {
self.backgroundColor = UIColor.clear
}
}
}
// MARK: Private • FieldDelegate
private extension QMultiTextField {
class FieldDelegate : NSObject, UITextViewDelegate {
public weak var field: QMultiTextField?
public init(field: QMultiTextField?) {
self.field = field
super.init()
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
guard let field = self.field, let closure = field.onShouldBeginEditing else { return true }
return closure(field)
}
public func textViewDidBeginEditing(_ textView: UITextView) {
guard let field = self.field else { return }
if let closure = field.onBeginEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.beginEditing(multiTextField: field)
})
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
guard let field = self.field, let closure = field.onShouldEndEditing else { return true }
return closure(field)
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard let field = self.field else { return }
if let closure = field.onEndEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.endEditing(multiTextField: field)
})
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let field = self.field else { return true }
var sourceText = textView.text ?? ""
if let sourceTextRange = sourceText.range(from: range) {
sourceText = sourceText.replacingCharacters(in: sourceTextRange, with: text)
}
var isValid: Bool = true
if let font = textView.font, field.maximumNumberOfCharecters > 0 || field.maximumNumberOfLines > 0 {
if field.maximumNumberOfCharecters > 0 {
if sourceText.count > field.maximumNumberOfCharecters {
isValid = false
}
}
if field.maximumNumberOfLines > 0 {
let allowWidth = textView.frame.inset(by: textView.textContainerInset).width - (2.0 * textView.textContainer.lineFragmentPadding)
let textSize = textView.textStorage.boundingRect(
with: CGSize(width: allowWidth, height: CGFloat.greatestFiniteMagnitude),
options: [ .usesLineFragmentOrigin ],
context: nil
)
if UInt(textSize.height / font.lineHeight) > field.maximumNumberOfLines {
isValid = false
}
}
}
return isValid
}
public func textViewDidChange(_ textView: UITextView) {
guard let field = self.field else { return }
field._updatePlaceholderVisibility()
let height = field._textHeight()
if abs(field.textHeight - height) > CGFloat.leastNonzeroMagnitude {
field.textHeight = height
UIView.animate(withDuration: 0.1, animations: {
if let onChangedHeight = field.onChangedHeight {
onChangedHeight(field)
}
field._observer.notify({ (observer) in
observer.changed(multiTextField: field, height: height)
})
textView.scrollRangeToVisible(textView.selectedRange)
}, completion: { _ in
textView.scrollRangeToVisible(textView.selectedRange)
})
}
if let closure = field.onEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.editing(multiTextField: field)
})
if let form = field.form {
form.validation()
}
}
}
}
// MARK: UITextInputTraits
extension QMultiTextField : UITextInputTraits {
public var autocapitalizationType: UITextAutocapitalizationType {
set(value) { self._field.autocapitalizationType = value }
get { return self._field.autocapitalizationType }
}
public var autocorrectionType: UITextAutocorrectionType {
set(value) { self._field.autocorrectionType = value }
get { return self._field.autocorrectionType }
}
public var spellCheckingType: UITextSpellCheckingType {
set(value) { self._field.spellCheckingType = value }
get { return self._field.spellCheckingType }
}
public var keyboardType: UIKeyboardType {
set(value) { self._field.keyboardType = value }
get { return self._field.keyboardType }
}
public var keyboardAppearance: UIKeyboardAppearance {
set(value) { self._field.keyboardAppearance = value }
get { return self._field.keyboardAppearance }
}
public var returnKeyType: UIReturnKeyType {
set(value) { self._field.returnKeyType = value }
get { return self._field.returnKeyType }
}
public var enablesReturnKeyAutomatically: Bool {
set(value) { self._field.enablesReturnKeyAutomatically = value }
get { return self._field.enablesReturnKeyAutomatically }
}
public var isSecureTextEntry: Bool {
set(value) { self._field.isSecureTextEntry = value }
get { return self._field.isSecureTextEntry }
}
@available(iOS 10.0, *)
public var textContentType: UITextContentType! {
set(value) { self._field.textContentType = value }
get { return self._field.textContentType }
}
}
| mit |
octoblu/MeshbluBeaconKit-iOS | Example/Pods/Cent/Cent/Cent/Array.swift | 5 | 6162 | //
// Array.swift
// Cent
//
// Created by Ankur Patel on 6/28/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
import Dollar
internal extension Array {
/// Creates an array of elements from the specified indexes, or keys, of the collection.
/// Indexes may be specified as individual arguments or as arrays of indexes.
///
/// :param array The array to source from
/// :param indexes Get elements from these indexes
/// :return New array with elements from the indexes specified.
func at(indexes: Int...) -> [Element] {
return $.at(self, indexes: indexes)
}
/// Cycles through the array n times passing each element into the callback function
///
/// :param times Number of times to cycle through the array
/// :param callback function to call with the element
func cycle<U>(times: Int, callback: (Element) -> U) {
$.cycle(self, times, callback: callback)
}
/// Cycles through the array indefinetly passing each element into the callback function
///
/// :param callback function to call with the element
func cycle<U>(callback: (Element) -> U) {
$.cycle(self, callback: callback)
}
/// For each item in the array invoke the callback by passing the elem
///
/// :param callback The callback function to invoke that take an element
func eachWithIndex(callback: (Int, Element) -> ()) -> [Element] {
for (index, elem) in enumerate(self) {
callback(index, elem)
}
return self
}
/// For each item in the array invoke the callback by passing the elem along with the index
///
/// :param callback The callback function to invoke
func each(callback: (Element) -> ()) -> [Element] {
self.eachWithIndex { (index, elem) -> () in
callback(elem)
}
return self
}
/// Checks if the given callback returns true value for all items in the array.
///
/// :param array The array to check.
/// :param callback Check whether element value is true or false.
/// :return First element from the array.
func every(callback: (Element) -> Bool) -> Bool {
return $.every(self, callback: callback)
}
/// Get element from an array at the given index which can be negative
/// to find elements from the end of the array
///
/// :param index Can be positive or negative to find from end of the array
/// :param orElse Default value to use if index is out of bounds
/// :return Element fetched from the array or the default value passed in orElse
func fetch(index: Int, orElse: Element? = .None) -> Element! {
return $.fetch(self, index, orElse: orElse)
}
/// This method is like find except that it returns the index of the first element
/// that passes the callback check.
///
/// :param array The array to search for the element in.
/// :param callback Function used to figure out whether element is the same.
/// :return First element's index from the array found using the callback.
func findIndex(callback: (Element) -> Bool) -> Int? {
return $.findIndex(self, callback: callback)
}
/// This method is like findIndex except that it iterates over elements of the array
/// from right to left.
///
/// :param array The array to search for the element in.
/// :param callback Function used to figure out whether element is the same.
/// :return Last element's index from the array found using the callback.
func findLastIndex(callback: (Element) -> Bool) -> Int? {
return $.findLastIndex(self, callback: callback)
}
/// Gets the first element in the array.
///
/// :param array The array to wrap.
/// :return First element from the array.
func first() -> Element? {
return $.first(self)
}
/// Flattens the array
///
/// :return Flatten array of elements
func flatten() -> [Element] {
return $.flatten(self)
}
/// Get element at index
///
/// :param index The index in the array
/// :return Element at that index
func get(index: Int) -> Element! {
return self.fetch(index)
}
/// Gets all but the last element or last n elements of an array.
///
/// :param array The array to source from.
/// :param numElements The number of elements to ignore in the end.
/// :return Array of initial values.
func initial(numElements: Int? = 1) -> [Element] {
return $.initial(self, numElements: numElements!)
}
/// Gets the last element from the array.
///
/// :param array The array to source from.
/// :return Last element from the array.
func last() -> Element? {
return $.last(self)
}
/// The opposite of initial this method gets all but the first element or first n elements of an array.
///
/// :param array The array to source from.
/// :param numElements The number of elements to exclude from the beginning.
/// :return The rest of the elements.
func rest(numElements: Int? = 1) -> [Element] {
return $.rest(self, numElements: numElements!)
}
/// Retrieves the minimum value in an array.
///
/// :param array The array to source from.
/// :return Minimum value from array.
func min<T: Comparable>() -> T? {
return $.min(map { $0 as! T })
}
/// Retrieves the maximum value in an array.
///
/// :param array The array to source from.
/// :return Maximum element in array.
func max<T: Comparable>() -> T? {
return $.max(map { $0 as! T })
}
}
/// Overloaded operator to appends another array to an array
///
/// :return array with the element appended in the end
public func <<<T>(inout left: [T], right: [T]) -> [T] {
left += right
return left
}
/// Overloaded operator to append element to an array
///
/// :return array with the element appended in the end
public func <<<T>(inout array: [T], elem: T) -> [T] {
array.append(elem)
return array
}
| mit |
Shivol/Swift-CS333 | playgrounds/uiKit/uiKitCatalog/UIKitCatalog/StackViewController.swift | 3 | 3835 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates different options for manipulating UIStackView content.
*/
import UIKit
class StackViewController: UIViewController {
// MARK: - Properties
@IBOutlet var furtherDetailStackView: UIStackView!
@IBOutlet var plusButton: UIButton!
@IBOutlet var addRemoveExampleStackView: UIStackView!
@IBOutlet var addArrangedViewButton: UIButton!
@IBOutlet var removeArrangedViewButton: UIButton!
let maximumArrangedSubviewCount = 3
// MARK: - View Life Cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
furtherDetailStackView.isHidden = true
plusButton.isHidden = false
updateAddRemoveButtons()
}
// MARK: - Actions
@IBAction func showFurtherDetail(_: AnyObject) {
// Animate the changes by performing them in a `UIView` animation block.
UIView.animate(withDuration: 0.25, animations: {
// Reveal the further details stack view and hide the plus button.
self.furtherDetailStackView.isHidden = false
self.plusButton.isHidden = true
})
}
@IBAction func hideFurtherDetail(_: AnyObject) {
// Animate the changes by performing them in a `UIView` animation block.
UIView.animate(withDuration: 0.25, animations: {
// Hide the further details stack view and reveal the plus button.
self.furtherDetailStackView.isHidden = true
self.plusButton.isHidden = false
})
}
@IBAction func addArrangedSubviewToStack(_: AnyObject) {
// Create a simple, fixed-size, square view to add to the stack view
let newViewSize = CGSize(width: 50, height: 50)
let newView = UIView(frame: CGRect(origin: CGPoint.zero, size: newViewSize))
newView.backgroundColor = randomColor()
newView.widthAnchor.constraint(equalToConstant: newViewSize.width).isActive = true
newView.heightAnchor.constraint(equalToConstant: newViewSize.height).isActive = true
/*
Adding an arranged subview automatically adds it as a child of the
stack view.
*/
addRemoveExampleStackView.addArrangedSubview(newView)
updateAddRemoveButtons()
}
@IBAction func removeArrangedSubviewFromStack(_: AnyObject) {
// Make sure there is an arranged view to remove.
guard let viewToRemove = addRemoveExampleStackView.arrangedSubviews.last else { return }
addRemoveExampleStackView.removeArrangedSubview(viewToRemove)
/*
Calling `removeArrangedSubview` does not remove the provided view from
the stack view's `subviews` array. Since we no longer want the view
we removed to appear, we have to explicitly remove it from its superview.
*/
viewToRemove.removeFromSuperview()
updateAddRemoveButtons()
}
// MARK: - Convenience
fileprivate func updateAddRemoveButtons() {
let arrangedSubviewCount = addRemoveExampleStackView.arrangedSubviews.count
addArrangedViewButton.isEnabled = arrangedSubviewCount < maximumArrangedSubviewCount
removeArrangedViewButton.isEnabled = arrangedSubviewCount > 0
}
fileprivate func randomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(255)) / 255.0
let green = CGFloat(arc4random_uniform(255)) / 255.0
let blue = CGFloat(arc4random_uniform(255)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| mit |
6ag/BaoKanIOS | BaoKanIOS/Classes/Module/Profile/Controller/JFBaseTableViewController.swift | 1 | 2656 | //
// JFBaseTableViewController.swift
// BaoKanIOS
//
// Created by zhoujianfeng on 16/5/5.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
class JFBaseTableViewController: UITableViewController {
/// 组模型数组
var groupModels: [JFProfileCellGroupModel]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.sectionHeaderHeight = 0.01
tableView.separatorStyle = .none
tableView.register(JFProfileCell.self, forCellReuseIdentifier: "profileCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return groupModels?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupModels![section].cells?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell") as! JFProfileCell
let groupModel = groupModels![indexPath.section]
let cellModel = groupModel.cells![indexPath.row]
cell.cellModel = cellModel
cell.showLineView = !(indexPath.row == groupModel.cells!.count - 1)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groupModels![section].footerTitle
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return groupModels![section].headerTitle
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cellModel = groupModels![indexPath.section].cells![indexPath.row]
// 如果有可执行代码就执行
if cellModel.operation != nil {
cellModel.operation!()
return
}
// 如果是箭头类型就跳转控制器
if cellModel .isKind(of: JFProfileCellArrowModel.self) {
let cellArrow = cellModel as! JFProfileCellArrowModel
/// 目标控制器类
let destinationVcClass = cellArrow.destinationVc as! UIViewController.Type
let destinationVc = destinationVcClass.init()
destinationVc.title = cellArrow.title
navigationController?.pushViewController(destinationVc, animated: true)
}
}
}
| apache-2.0 |
exercism/xswift | exercises/dominoes/Sources/Dominoes/DominoesExample.swift | 2 | 4900 | struct Dominoes {
let singles: [Bone]
let doubles: [Bone]
var chained: Bool {
if singles.isEmpty && doubles.count == 1 { return true }
let (success, result) = chainning(swapDuplicate(singles))
if doubles.isEmpty {
return success
} else if success == true {
return doubles.count == doubles.filter({ each in return result.contains(where: { e in return e.value.head == each.value.head }) }).count
} else {
return false
}
}
private func swapDuplicate(_ input: [Bone]) -> [Bone] {
var unique = [Bone]()
for each in input {
if unique.contains(each) {
unique.insert(Bone(each.value.tail, each.value.head), at: 0)
} else {
unique.append(each)
}
}
return unique
}
private func chainning(_ input: [Bone]) -> (Bool, [Bone]) {
var matched = input
guard !matched.isEmpty else { return (false, []) }
let total = matched.count - 1
for index in 0...total {
for innerIndex in 0...total {
matched[index].connect(matched[innerIndex])
}
}
return (matched.filter({ $0.connected >= 2 }).count == matched.count) ?
(true, matched) : (false, [])
}
init(_ input: [(Int, Int)]) {
var singles = [Bone]()
var doubles = [Bone]()
for each in input {
if each.0 == each.1 {
doubles.append(Bone(each.0, each.1))
} else {
singles.append(Bone(each.0, each.1))
}
}
self.singles = singles
self.doubles = doubles
}
}
func == (lhs: Bone, rhs: Bone) -> Bool {
return lhs.value.head == rhs.value.head && lhs.value.tail == rhs.value.tail
}
class Bone: CustomStringConvertible, Equatable {
let value:(head: Int, tail: Int)
var connected: Int = 0
var available: Int?
var connectedTo: Bone?
var description: String {
return "\(value)|\(connected)|\(String(describing: available)) "
}
@discardableResult
func connect(_ input: Bone) -> Bool {
guard self !== input else { return false }
guard self !== input.connectedTo else { return false }
var toReturn = false
func oneZero() {
if available == input.value.head {
self.available = nil
input.available = input.value.tail
toReturn = true
}
if available == input.value.tail {
self.available = nil
input.available = input.value.head
toReturn = true
}
}
func zeroOne() {
if available == value.head {
input.available = nil
self.available = value.tail
toReturn = true
}
if available == value.tail {
input.available = nil
self.available = value.head
toReturn = true
}
}
func oneOne() {
if available == input.available {
self.available = nil
input.available = nil
toReturn = true
}
}
func zeroZero() {
if value.head == input.value.head {
available = value.tail
input.available = input.value.tail
connectedTo = input
toReturn = true
}
if value.tail == input.value.tail {
available = value.head
input.available = input.value.head
connectedTo = input
toReturn = true
}
if value.head == input.value.tail {
available = value.tail
input.available = input.value.head
connectedTo = input
toReturn = true
}
if value.tail == input.value.head {
available = value.head
input.available = input.value.tail
connectedTo = input
toReturn = true
}
}
switch (connected, input.connected) {
case (1, 0):
guard available != nil else { return false }
oneZero()
case (0, 1):
guard input.available != nil else { return false }
zeroOne()
case (1, 1):
oneOne()
case (0, 0):
zeroZero()
default:
toReturn = false
}
if toReturn {
connected += 1
input.connected += 1
return true
} else {
return false
}
}
init(_ head: Int, _ tail: Int) {
self.value.head = head
self.value.tail = tail
}
}
| mit |
dduan/swift | test/Constraints/function.swift | 1 | 2214 | // RUN: %target-parse-verify-swift
func f0(x: Float) -> Float {}
func f1(x: Float) -> Float {}
func f2(@autoclosure x: () -> Float) {}
var f : Float
f0(f0(f))
f0(1)
f1(f1(f))
f2(f)
f2(1.0)
func call_lvalue(@autoclosure rhs: () -> Bool) -> Bool {
return rhs()
}
// Function returns
func weirdCast<T, U>(x: T) -> U {}
func ff() -> (Int) -> (Float) { return weirdCast }
// Block <-> function conversions
var funct: Int -> Int = { $0 }
var block: @convention(block) Int -> Int = funct
funct = block
block = funct
// Application of implicitly unwrapped optional functions
var optFunc: (String -> String)! = { $0 }
var s: String = optFunc("hi")
// <rdar://problem/17652759> Default arguments cause crash with tuple permutation
func testArgumentShuffle(first: Int = 7, third: Int = 9) {
}
testArgumentShuffle(third: 1, 2)
func rejectsAssertStringLiteral() {
assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
}
// <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads
func process(line: UInt = #line, _ fn: () -> Void) {}
func process(line: UInt = #line) -> Int { return 0 }
func dangerous() throws {}
func test() {
process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}}
try dangerous()
test()
}
}
// <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic
class A {
func a(text:String) {
}
func a(text:String, something:Int?=nil) {
}
}
A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}}
// <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type
func r22451001() -> AnyObject {}
print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}}
// SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler
func sr590(x: Any) {}
sr590(3,4) // expected-error {{extra argument in call}}
| apache-2.0 |
kinwahlai/YetAnotherHTTPStub | ExampleTests/ExampleWithAlamofireTests.swift | 1 | 11095 | //
// ExampleWithAlamofireTests.swift
// ExampleWithAlamofireTests
//
// Created by Darren Lai on 7/15/17.
// Copyright © 2017 KinWahLai. All rights reserved.
//
import XCTest
import YetAnotherHTTPStub
@testable import Example
class ExampleWithAlamofireTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testSimpleExample() {
let bundle = Bundle(for: ExampleWithAlamofireTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonData(data, status: 200))
}
let expect = expectation(description: "")
let service = ServiceUsingAlamofire()
service.getRequest { (dict, _) in
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
func testMultipleRequestExample() {
let bundle = Bundle(for: ExampleWithAlamofireTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonData(data, status: 200))
session.whenRequest(matcher: http(.get, uri: "/get?show_env=1&page=1"))
.thenResponse(responseBuilder: jsonString("{\"args\":{\"page\": 1,\"show_env\": 1}}", status: 200))
}
let service = ServiceUsingAlamofire()
service.getRequest { (dict, _) in
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect1.fulfill()
}
service.getRequest(with: "https://httpbin.org/get?show_env=1&page=1") { (dict, _) in
let args = dict!["args"] as! [String: Any]
XCTAssertNotNil(args)
XCTAssertEqual(args["show_env"] as! Int, 1)
expect2.fulfill()
}
wait(for: [expect1, expect2], timeout: 5)
}
func testMultipleResponseExample() {
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
let expect3 = expectation(description: "3")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/polling"))
.thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200))
}
let service = ServiceUsingAlamofire()
let response3: HttpbinService.ResquestResponse = { (dict, _) in
let dictInt = dict as! [String: Int]
XCTAssertEqual(dictInt["status"], 1)
expect3.fulfill()
}
let response2: HttpbinService.ResquestResponse = { [response3] (dict, _) in
expect2.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response3)
}
let response1: HttpbinService.ResquestResponse = { [response2] (dict, _) in
expect1.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response2)
}
service.getRequest(with: "https://httpbin.org/polling", response1)
wait(for: [expect1, expect2, expect3], timeout: 5)
}
func testSimpleExampleWithDelay() {
let delay: TimeInterval = 5
let bundle = Bundle(for: ExampleWithAlamofireTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(withDelay: delay, responseBuilder: jsonData(data, status: 200))
}
let service = ServiceUsingAlamofire()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect.fulfill()
}
waitForExpectations(timeout: delay + 1) { (error) in
XCTAssertNil(error)
}
}
// TODO: fix the test that failed after AF 5 upgrade
func xtestRequestFailedIfStubSessionSetupIncomplete() {
let customQueue = DispatchQueue(label: "custom.queue")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/noResponse"))
session.whenRequest(matcher: http(.get, uri: "/partialResponse"))
.responseOn(queue: customQueue)
}
let service1 = ServiceUsingAlamofire()
let service2 = ServiceUsingAlamofire()
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
let response2: HttpbinService.ResquestResponse = { (_, error) in
if let err = error as NSError? {
XCTAssertEqual(err.code, -959)
XCTAssertEqual(err.userInfo["message"] as? String, "Cannot process partial response for this request https://httpbin.org/partialResponse")
} else {
XCTFail()
}
expect2.fulfill()
}
let response1: HttpbinService.ResquestResponse = { (_, error) in
if let err = error as NSError? {
XCTAssertEqual(err.code, -979)
XCTAssertEqual(err.userInfo["message"] as? String, "There isn't any(more) response for this request https://httpbin.org/noResponse")
} else {
XCTFail()
}
expect1.fulfill()
}
service1.getRequest(with: "https://httpbin.org/noResponse", response1)
service2.getRequest(with: "https://httpbin.org/partialResponse", response2)
wait(for: [expect1, expect2], timeout: 5)
}
func testExampleUsingFileContentBuilder() {
guard let filePath: URL = Bundle(for: ExampleWithAlamofireTests.self).url(forResource: "GET", withExtension: "json") else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent
}
let service = ServiceUsingAlamofire()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
XCTAssertNil(error)
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
func testRepeatableResponseExample() {
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
let expect3 = expectation(description: "3")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/polling"))
.thenResponse(repeat: 2, responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200))
}
let service = ServiceUsingAlamofire()
let response3: HttpbinService.ResquestResponse = { (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
let dictInt = dict as! [String: Int]
XCTAssertEqual(dictInt["status"], 1)
expect3.fulfill()
}
let response2: HttpbinService.ResquestResponse = { [response3] (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect2.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response3)
}
let response1: HttpbinService.ResquestResponse = { [response2] (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect1.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response2)
}
service.getRequest(with: "https://httpbin.org/polling", response1)
wait(for: [expect1, expect2, expect3], timeout: 5)
}
func testGetNotifyAfterStubResponseReplied() {
var gotNotify: String? = nil
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(configurator: { (param) in
param.setResponseDelay(2)
.setBuilder(builder: jsonString("{\"hello\":\"world\"}", status: 200))
.setPostReply {
gotNotify = "post reply notification"
}
})
}
let service = ServiceUsingAlamofire()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
XCTAssertEqual(gotNotify, "post reply notification")
}
func testPostARequest() {
guard let filePath: URL = Bundle(for: ExampleWithAlamofireTests.self).url(forResource: "POST", withExtension: "json") else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: everything)
.thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent
}
let service = ServiceUsingAlamofire()
let expect = expectation(description: "")
service.post(["username": "Darren"]) { (dict, error) in
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
let url = dict!["url"] as! String
XCTAssertEqual(url, "https://httpbin.org/post")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
}
| mit |
matrix-org/matrix-ios-sdk | MatrixSDK/Space/MXSpaceService.swift | 1 | 40898 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// MXSpaceService error
public enum MXSpaceServiceError: Int, Error {
case spaceNotFound
case unknown
}
// MARK: - MXSpaceService errors
extension MXSpaceServiceError: CustomNSError {
public static let errorDomain = "org.matrix.sdk.spaceService"
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [:]
}
}
// MARK: - MXSpaceService notification constants
extension MXSpaceService {
/// Posted once the first graph as been built or loaded
public static let didInitialise = Notification.Name("MXSpaceServiceDidInitialise")
/// Posted once the graph of rooms is up and running
public static let didBuildSpaceGraph = Notification.Name("MXSpaceServiceDidBuildSpaceGraph")
}
/// MXSpaceService enables to handle spaces.
@objcMembers
public class MXSpaceService: NSObject {
// MARK: - Properties
private let spacesPerIdReadWriteQueue: DispatchQueue
private unowned let session: MXSession
private lazy var stateEventBuilder: MXRoomInitialStateEventBuilder = {
return MXRoomInitialStateEventBuilder()
}()
private let roomTypeMapper: MXRoomTypeMapper
private let processingQueue: DispatchQueue
private let sdkProcessingQueue: DispatchQueue
private let completionQueue: DispatchQueue
private var spacesPerId: [String: MXSpace] = [:]
private var isGraphBuilding = false;
private var isClosed = false;
private var sessionStateDidChangeObserver: Any?
private var graph: MXSpaceGraphData = MXSpaceGraphData() {
didSet {
var spacesPerId: [String:MXSpace] = [:]
self.graph.spaceRoomIds.forEach { spaceId in
if let space = self.getSpace(withId: spaceId) {
spacesPerId[spaceId] = space
}
}
spacesPerIdReadWriteQueue.sync(flags: .barrier) {
self.spacesPerId = spacesPerId
}
}
}
// MARK: Public
/// The instance of `MXSpaceNotificationCounter` that computes the number of unread messages for each space
public let notificationCounter: MXSpaceNotificationCounter
/// List of `MXSpace` instances of the high level spaces.
public var rootSpaces: [MXSpace] {
return self.graph.rootSpaceIds.compactMap { spaceId in
self.getSpace(withId: spaceId)
}
}
/// List of `MXRoomSummary` of the high level spaces.
public var rootSpaceSummaries: [MXRoomSummary] {
return self.graph.rootSpaceIds.compactMap { spaceId in
self.session.roomSummary(withRoomId: spaceId)
}
}
/// List of `MXRoomSummary` of all spaces known by the user.
public var spaceSummaries: [MXRoomSummary] {
return self.graph.spaceRoomIds.compactMap { spaceId in
self.session.roomSummary(withRoomId: spaceId)
}
}
/// `true` if the `MXSpaceService` instance needs to be updated (e.g. the instance was busy while `handleSync` was called). `false` otherwise
public private(set) var needsUpdate: Bool = true
/// Set it to `false` if you want to temporarily disable graph update. This will be set automatically to `true` after next sync of the `MXSession`.
public var graphUpdateEnabled = true
/// List of ID of all the ancestors (direct parent spaces and parent spaces of the direct parent spaces) by room ID.
public var ancestorsPerRoomId: [String:Set<String>] {
return graph.ancestorsPerRoomId
}
/// The `MXSpaceService` instance is initialised if a previously saved graph has been restored or after the first sync.
public private(set) var isInitialised = false {
didSet {
if !oldValue && isInitialised {
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didInitialise, object: self)
}
}
}
}
// MARK: - Setup
public init(session: MXSession) {
self.session = session
self.notificationCounter = MXSpaceNotificationCounter(session: session)
self.roomTypeMapper = MXRoomTypeMapper(defaultRoomType: .room)
self.processingQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.processingQueue", attributes: .concurrent)
self.completionQueue = DispatchQueue.main
self.sdkProcessingQueue = DispatchQueue.main
self.spacesPerIdReadWriteQueue = DispatchQueue(
label: "org.matrix.sdk.MXSpaceService.spacesPerIdReadWriteQueue",
attributes: .concurrent
)
super.init()
self.registerNotificationObservers()
}
deinit {
unregisterNotificationObservers()
}
// MARK: - Public
/// close the service and free all data
public func close() {
self.isClosed = true
self.graph = MXSpaceGraphData()
self.notificationCounter.close()
self.isInitialised = false
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
/// Loads graph from the given store
public func loadData() {
self.processingQueue.async {
var _myUserId: String?
var _myDeviceId: String?
self.sdkProcessingQueue.sync {
_myUserId = self.session.myUserId
_myDeviceId = self.session.myDeviceId
}
guard let myUserId = _myUserId, let myDeviceId = _myDeviceId else {
MXLog.error("[MXSpaceService] loadData: Unexpectedly found nil for myUserId and/or myDeviceId")
return
}
let store = MXSpaceFileStore(userId: myUserId, deviceId: myDeviceId)
if let loadedGraph = store.loadSpaceGraphData() {
self.graph = loadedGraph
self.completionQueue.async {
self.isInitialised = true
self.notificationCounter.computeNotificationCount()
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
}
}
/// Returns the set of direct parent IDs of the given room
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: set of direct parent IDs of the given room. Empty set if the room has no parent.
public func directParentIds(ofRoomWithId roomId: String) -> Set<String> {
return graph.parentIdsPerRoomId[roomId] ?? Set()
}
/// Returns the set of direct parent IDs of the given room for which the room is suggested or not according to the request.
/// - Parameters:
/// - roomId: ID of the room
/// - suggested: If `true` the method will return the parent IDs where the room is suggested. If `false` the method will return the parent IDs where the room is NOT suggested
/// - Returns: set of direct parent IDs of the given room. Empty set if the room has no parent.
public func directParentIds(ofRoomWithId roomId: String, whereRoomIsSuggested suggested: Bool) -> Set<String> {
return directParentIds(ofRoomWithId: roomId).filter { spaceId in
guard let space = spacesPerId[spaceId] else {
return false
}
return (suggested && space.suggestedRoomIds.contains(roomId)) || (!suggested && !space.suggestedRoomIds.contains(roomId))
}
}
/// Allows to know if a given room is a descendant of a given space
/// - Parameters:
/// - roomId: ID of the room
/// - spaceId: ID of the space
/// - Returns: `true` if the room with the given ID is an ancestor of the space with the given ID .`false` otherwise
public func isRoom(withId roomId: String, descendantOf spaceId: String) -> Bool {
return self.graph.descendantsPerRoomId[spaceId]?.contains(roomId) ?? false
}
/// Allows to know if the room is oprhnaed (e.g. has no ancestor)
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: `true` if the room with the given ID is orphaned .`false` otherwise
public func isOrphanedRoom(withId roomId: String) -> Bool {
return self.graph.orphanedRoomIds.contains(roomId) || self.graph.orphanedDirectRoomIds.contains(roomId)
}
/// Returns the first ancestor which is a root space
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: Instance of the ancestor if found. `nil` otherwise
public func firstRootAncestorForRoom(withId roomId: String) -> MXSpace? {
if let ancestorIds = ancestorsPerRoomId[roomId] {
for ancestorId in ancestorIds where ancestorsPerRoomId[ancestorId] == nil {
return spacesPerId[ancestorId]
}
}
return nil
}
/// Handle a sync response
/// - Parameters:
/// - syncResponse: The sync response object
public func handleSyncResponse(_ syncResponse: MXSyncResponse) {
guard self.needsUpdate || !(syncResponse.rooms?.join?.isEmpty ?? true) || !(syncResponse.rooms?.invite?.isEmpty ?? true) || !(syncResponse.rooms?.leave?.isEmpty ?? true) || !(syncResponse.toDevice?.events.isEmpty ?? true) else {
return
}
self.buildGraph()
}
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(with parameters: MXSpaceCreationParameters, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
return self.session.createRoom(parameters: parameters) { (response) in
switch response {
case .success(let room):
let space: MXSpace = MXSpace(roomId: room.roomId, session:self.session)
self.completionQueue.async {
completion(.success(space))
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - aliasLocalPart: local part of the alias
/// (e.g. for the alias "#my_alias:example.org", the local part is "my_alias")
/// - inviteArray: list of invited user IDs
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(withName name: String?, topic: String?, isPublic: Bool, aliasLocalPart: String? = nil, inviteArray: [String]? = nil, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
let parameters = MXSpaceCreationParameters()
parameters.name = name
parameters.topic = topic
parameters.preset = isPublic ? kMXRoomPresetPublicChat : kMXRoomPresetPrivateChat
parameters.visibility = isPublic ? kMXRoomDirectoryVisibilityPublic : kMXRoomDirectoryVisibilityPrivate
parameters.inviteArray = inviteArray
if isPublic {
parameters.roomAlias = aliasLocalPart
let guestAccessStateEvent = self.stateEventBuilder.buildGuestAccessEvent(withAccess: .canJoin)
parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent)
let historyVisibilityStateEvent = self.stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .worldReadable)
parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent)
parameters.powerLevelContentOverride?.invite = 0 // default
} else {
parameters.powerLevelContentOverride?.invite = 50 // moderator
}
return self.createSpace(with: parameters, completion: completion)
}
/// Get a space from a roomId.
/// - Parameter spaceId: The id of the space.
/// - Returns: A MXSpace with the associated roomId or null if room doesn't exists or the room type is not space.
public func getSpace(withId spaceId: String) -> MXSpace? {
var space: MXSpace?
spacesPerIdReadWriteQueue.sync {
space = self.spacesPerId[spaceId]
}
if space == nil, let newSpace = self.session.room(withRoomId: spaceId)?.toSpace() {
space = newSpace
spacesPerIdReadWriteQueue.sync(flags: .barrier) {
self.spacesPerId[spaceId] = newSpace
}
}
return space
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func getSpaceChildrenForSpace(withId spaceId: String,
suggestedOnly: Bool,
limit: Int?,
maxDepth: Int?,
paginationToken: String?,
completion: @escaping (MXResponse<MXSpaceChildrenSummary>) -> Void) -> MXHTTPOperation {
return self.session.matrixRestClient.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit, maxDepth: maxDepth, paginationToken: paginationToken) { (response) in
switch response {
case .success(let spaceChildrenResponse):
self.processingQueue.async { [weak self] in
guard let self = self else {
return
}
guard let rooms = spaceChildrenResponse.rooms else {
// We should have at least one room for the requested space
self.completionQueue.async {
completion(.failure(MXSpaceServiceError.spaceNotFound))
}
return
}
// Build room hierarchy and events
var childrenIdsPerChildRoomId: [String: [String]] = [:]
var parentIdsPerChildRoomId: [String:Set<String>] = [:]
var spaceChildEventsPerChildRoomId: [String:[String:Any]] = [:]
for room in spaceChildrenResponse.rooms ?? [] {
for event in room.childrenState ?? [] where event.wireContent.count > 0 {
spaceChildEventsPerChildRoomId[event.stateKey] = event.wireContent
var parentIds = parentIdsPerChildRoomId[event.stateKey] ?? Set()
parentIds.insert(room.roomId)
parentIdsPerChildRoomId[event.stateKey] = parentIds
var childrenIds = childrenIdsPerChildRoomId[room.roomId] ?? []
childrenIds.append(event.stateKey)
childrenIdsPerChildRoomId[room.roomId] = childrenIds
}
}
var spaceInfo: MXSpaceChildInfo?
if let rootSpaceChildSummaryResponse = rooms.first(where: { spaceResponse -> Bool in spaceResponse.roomId == spaceId}) {
spaceInfo = self.createSpaceChildInfo(with: rootSpaceChildSummaryResponse, childrenIds: childrenIdsPerChildRoomId[spaceId], childEvents: spaceChildEventsPerChildRoomId[spaceId])
}
// Build the child summaries of the queried space
let childInfos = self.spaceChildInfos(from: spaceChildrenResponse, excludedSpaceId: spaceId, childrenIdsPerChildRoomId: childrenIdsPerChildRoomId, parentIdsPerChildRoomId: parentIdsPerChildRoomId, spaceChildEventsPerChildRoomId: spaceChildEventsPerChildRoomId)
let spaceChildrenSummary = MXSpaceChildrenSummary(spaceInfo: spaceInfo, childInfos: childInfos, nextBatch: spaceChildrenResponse.nextBatch)
self.completionQueue.async {
completion(.success(spaceChildrenSummary))
}
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
// MARK: - Space graph computation
private class PrepareDataResult {
private var _spaces: [MXSpace] = []
private var _spacesPerId: [String : MXSpace] = [:]
private var _directRoomIdsPerMemberId: [String: [String]] = [:]
private var computingSpaces: Set<String> = Set()
private var computingDirectRooms: Set<String> = Set()
var spaces: [MXSpace] {
var result: [MXSpace] = []
self.serialQueue.sync {
result = self._spaces
}
return result
}
var spacesPerId: [String : MXSpace] {
var result: [String : MXSpace] = [:]
self.serialQueue.sync {
result = self._spacesPerId
}
return result
}
var directRoomIdsPerMemberId: [String: [String]] {
var result: [String: [String]] = [:]
self.serialQueue.sync {
result = self._directRoomIdsPerMemberId
}
return result
}
var isPreparingData = true
var isComputing: Bool {
var isComputing = false
self.serialQueue.sync {
isComputing = !self.computingSpaces.isEmpty || !self.computingDirectRooms.isEmpty
}
return isComputing
}
private let serialQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.PrepareDataResult.serialQueue")
func add(space: MXSpace) {
self.serialQueue.sync {
self._spaces.append(space)
self._spacesPerId[space.spaceId] = space
}
}
func add(directRoom: MXRoom, toUserWithId userId: String) {
self.serialQueue.sync {
var rooms = self._directRoomIdsPerMemberId[userId] ?? []
rooms.append(directRoom.roomId)
self._directRoomIdsPerMemberId[userId] = rooms
}
}
func setComputing(_ isComputing: Bool, forSpace space: MXSpace) {
self.serialQueue.sync {
if isComputing {
computingSpaces.insert(space.spaceId)
} else {
computingSpaces.remove(space.spaceId)
}
}
}
func setComputing(_ isComputing: Bool, forDirectRoom room: MXRoom) {
self.serialQueue.sync {
if isComputing {
computingDirectRooms.insert(room.roomId)
} else {
computingDirectRooms.remove(room.roomId)
}
}
}
}
/// Build the graph of rooms
private func buildGraph() {
guard !self.isClosed && !self.isGraphBuilding && self.graphUpdateEnabled else {
MXLog.debug("[MXSpaceService] buildGraph: aborted: graph is building or disabled")
self.needsUpdate = true
return
}
self.isGraphBuilding = true
self.needsUpdate = false
let startDate = Date()
MXLog.debug("[MXSpaceService] buildGraph: started")
var directRoomIds = Set<String>()
let roomIds: [String] = self.session.rooms.compactMap { room in
if room.isDirect {
directRoomIds.insert(room.roomId)
}
return room.roomId
}
let output = PrepareDataResult()
MXLog.debug("[MXSpaceService] buildGraph: preparing data for \(roomIds.count) rooms")
self.prepareData(with: roomIds, index: 0, output: output) { result in
guard !self.isClosed else {
return
}
MXLog.debug("[MXSpaceService] buildGraph: data prepared in \(Date().timeIntervalSince(startDate))")
self.computSpaceGraph(with: result, roomIds: roomIds, directRoomIds: directRoomIds) { graph in
guard !self.isClosed else {
return
}
self.graph = graph
MXLog.debug("[MXSpaceService] buildGraph: ended after \(Date().timeIntervalSince(startDate))s")
self.isGraphBuilding = false
self.isInitialised = true
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
self.processingQueue.async {
var _myUserId: String?
var _myDeviceId: String?
self.sdkProcessingQueue.sync {
_myUserId = self.session.myUserId
_myDeviceId = self.session.myDeviceId
}
guard let myUserId = _myUserId, let myDeviceId = _myDeviceId else {
MXLog.error("[MXSpaceService] buildGraph: Unexpectedly found nil for myUserId and/or myDeviceId")
return
}
let store = MXSpaceFileStore(userId: myUserId, deviceId: myDeviceId)
if !store.store(spaceGraphData: self.graph) {
MXLog.error("[MXSpaceService] buildGraph: failed to store space graph")
}
// TODO improve updateNotificationsCount and call the method to all spaces once subspaces will be supported
self.notificationCounter.computeNotificationCount()
}
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, completion: @escaping (_ result: PrepareDataResult) -> Void) {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
self.processingQueue.async {
guard index < roomIds.count else {
self.completionQueue.async {
output.isPreparingData = false
if !output.isComputing {
completion(output)
}
}
return
}
self.sdkProcessingQueue.async {
guard let room = self.session.room(withRoomId: roomIds[index]) else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
var space: MXSpace?
self.spacesPerIdReadWriteQueue.sync {
space = self.spacesPerId[room.roomId] ?? room.toSpace()
}
self.prepareData(with: roomIds, index: index, output: output, room: room, space: space, isRoomDirect: room.isDirect, directUserId: room.directUserId, completion: completion)
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, room: MXRoom, space _space: MXSpace?, isRoomDirect:Bool, directUserId _directUserId: String?, completion: @escaping (_ result: PrepareDataResult) -> Void) {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
self.processingQueue.async {
if let space = _space {
output.setComputing(true, forSpace: space)
space.readChildRoomsAndMembers {
output.setComputing(false, forSpace: space)
if !output.isPreparingData && !output.isComputing {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
completion(output)
}
}
output.add(space: space)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else if isRoomDirect {
if let directUserId = _directUserId {
output.add(directRoom: room, toUserWithId: directUserId)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else {
self.sdkProcessingQueue.async {
output.setComputing(true, forDirectRoom: room)
room.members { response in
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
guard let members = response.value as? MXRoomMembers else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
let membersId = members.members?.compactMap({ roomMember in
return roomMember.userId != self.session.myUserId ? roomMember.userId : nil
}) ?? []
self.processingQueue.async {
membersId.forEach { memberId in
output.add(directRoom: room, toUserWithId: memberId)
}
output.setComputing(false, forDirectRoom: room)
if !output.isPreparingData && !output.isComputing {
completion(output)
}
}
}
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
} else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
}
private func computSpaceGraph(with result: PrepareDataResult, roomIds: [String], directRoomIds: Set<String>, completion: @escaping (_ graph: MXSpaceGraphData) -> Void) {
let startDate = Date()
MXLog.debug("[MXSpaceService] computSpaceGraph: started for \(roomIds.count) rooms, \(directRoomIds.count) direct rooms, \(result.spaces.count) spaces, \(result.spaces.reduce(0, { $0 + $1.childSpaces.count })) child spaces, \(result.spaces.reduce(0, { $0 + $1.childRoomIds.count })) child rooms, \(result.spaces.reduce(0, { $0 + $1.otherMembersId.count })) other members, \(result.directRoomIdsPerMemberId.count) members")
self.processingQueue.async {
var parentIdsPerRoomId: [String : Set<String>] = [:]
result.spaces.forEach { space in
space.updateChildSpaces(with: result.spacesPerId)
space.updateChildDirectRooms(with: result.directRoomIdsPerMemberId)
space.childRoomIds.forEach { roomId in
var parentIds = parentIdsPerRoomId[roomId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
var parentIds = parentIdsPerRoomId[childSpace.spaceId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[childSpace.spaceId] = parentIds
}
}
let rootSpaces = result.spaces.filter { space in
return parentIdsPerRoomId[space.spaceId] == nil
}.sorted { space1, space2 in
let _space1Order = space1.order
let _space2Order = space2.order
if let space1Order = _space1Order, let space2Order = _space2Order {
return space1Order <= space2Order
}
if _space1Order == nil && _space2Order == nil {
return space1.spaceId <= space2.spaceId
} else if _space1Order != nil && _space2Order == nil {
return true
} else {
return false
}
}
var ancestorsPerRoomId: [String: Set<String>] = [:]
var descendantsPerRoomId: [String: Set<String>] = [:]
rootSpaces.forEach { space in
self.buildRoomHierarchy(with: space, visitedSpaceIds: [], ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
var orphanedRoomIds: Set<String> = Set<String>()
var orphanedDirectRoomIds: Set<String> = Set<String>()
for roomId in roomIds {
let isRoomDirect = directRoomIds.contains(roomId)
if !isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedRoomIds.insert(roomId)
} else if isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedDirectRoomIds.insert(roomId)
}
}
let graph = MXSpaceGraphData(
spaceRoomIds: result.spaces.map({ space in
space.spaceId
}),
parentIdsPerRoomId: parentIdsPerRoomId,
ancestorsPerRoomId: ancestorsPerRoomId,
descendantsPerRoomId: descendantsPerRoomId,
rootSpaceIds: rootSpaces.map({ space in
space.spaceId
}),
orphanedRoomIds: orphanedRoomIds,
orphanedDirectRoomIds: orphanedDirectRoomIds)
MXLog.debug("[MXSpaceService] computSpaceGraph: space graph computed in \(Date().timeIntervalSince(startDate))s")
self.completionQueue.async {
completion(graph)
}
}
}
private func buildRoomHierarchy(with space: MXSpace, visitedSpaceIds: [String], ancestorsPerRoomId: inout [String: Set<String>], descendantsPerRoomId: inout [String: Set<String>]) {
var visitedSpaceIds = visitedSpaceIds
visitedSpaceIds.append(space.spaceId)
space.childRoomIds.forEach { roomId in
var parentIds = ancestorsPerRoomId[roomId] ?? Set<String>()
visitedSpaceIds.forEach { spaceId in
parentIds.insert(spaceId)
var descendantIds = descendantsPerRoomId[spaceId] ?? Set<String>()
descendantIds.insert(roomId)
descendantsPerRoomId[spaceId] = descendantIds
}
ancestorsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
buildRoomHierarchy(with: childSpace, visitedSpaceIds: visitedSpaceIds, ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
}
// MARK: - Notification handling
private func registerNotificationObservers() {
self.sessionStateDidChangeObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxSessionStateDidChange, object: session, queue: nil) { [weak self] notification in
guard let session = self?.session, session.state == .storeDataReady else {
return
}
self?.loadData()
}
}
private func unregisterNotificationObservers() {
if let observer = self.sessionStateDidChangeObserver {
NotificationCenter.default.removeObserver(observer)
}
}
// MARK: - Private
private func createRoomSummary(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse) -> MXRoomSummary {
let roomId = spaceChildSummaryResponse.roomId
let roomTypeString = spaceChildSummaryResponse.roomType
let roomSummary: MXRoomSummary = MXRoomSummary(roomId: roomId, andMatrixSession: nil)
roomSummary.roomTypeString = roomTypeString
roomSummary.roomType = self.roomTypeMapper.roomType(from: roomTypeString)
let joinedMembersCount = UInt(spaceChildSummaryResponse.numJoinedMembers)
let membersCount = MXRoomMembersCount()
membersCount.joined = joinedMembersCount
membersCount.members = joinedMembersCount
roomSummary.membersCount = membersCount
roomSummary.displayname = spaceChildSummaryResponse.name
roomSummary.topic = spaceChildSummaryResponse.topic
roomSummary.avatar = spaceChildSummaryResponse.avatarUrl
roomSummary.isEncrypted = false
return roomSummary
}
private func spaceChildInfos(from spaceChildrenResponse: MXSpaceChildrenResponse, excludedSpaceId: String, childrenIdsPerChildRoomId: [String: [String]], parentIdsPerChildRoomId: [String:Set<String>], spaceChildEventsPerChildRoomId: [String:[String:Any]]) -> [MXSpaceChildInfo] {
guard let spaceChildSummaries = spaceChildrenResponse.rooms else {
return []
}
let childInfos: [MXSpaceChildInfo] = spaceChildSummaries.compactMap { (spaceChildSummaryResponse) -> MXSpaceChildInfo? in
let spaceId = spaceChildSummaryResponse.roomId
guard spaceId != excludedSpaceId else {
return nil
}
return self.createSpaceChildInfo(with: spaceChildSummaryResponse, childrenIds: childrenIdsPerChildRoomId[spaceId], childEvents: spaceChildEventsPerChildRoomId[spaceId])
}
return childInfos
}
private func createSpaceChildInfo(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse, childrenIds: [String]?, childEvents: [String:Any]?) -> MXSpaceChildInfo {
let roomTypeString = spaceChildSummaryResponse.roomType
let roomType = self.roomTypeMapper.roomType(from: roomTypeString)
return MXSpaceChildInfo(childRoomId: spaceChildSummaryResponse.roomId,
isKnown: true,
roomTypeString: roomTypeString,
roomType: roomType,
name: spaceChildSummaryResponse.name,
topic: spaceChildSummaryResponse.topic,
canonicalAlias: spaceChildSummaryResponse.canonicalAlias,
avatarUrl: spaceChildSummaryResponse.avatarUrl,
activeMemberCount: spaceChildSummaryResponse.numJoinedMembers,
autoJoin: childEvents?[kMXEventTypeStringAutoJoinKey] as? Bool ?? false,
suggested: childEvents?[kMXEventTypeStringSuggestedKey] as? Bool ?? false,
childrenIds: childrenIds ?? [])
}
}
// MARK: - Objective-C interface
extension MXSpaceService {
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@objc public func createSpace(with parameters: MXSpaceCreationParameters, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(with: parameters) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - aliasLocalPart: local part of the alias
/// (e.g. for the alias "#my_alias:example.org", the local part is "my_alias")
/// - inviteArray: list of invited user IDs
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func createSpace(withName name: String, topic: String?, isPublic: Bool, aliasLocalPart: String?, inviteArray: [String]?, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(withName: name, topic: topic, isPublic: isPublic, aliasLocalPart: aliasLocalPart, inviteArray: inviteArray) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int, maxDepth: Int, paginationToken: String?, success: @escaping (MXSpaceChildrenSummary) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit, maxDepth: maxDepth, paginationToken: paginationToken) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
}
// MARK: - Internal room additions
extension MXRoom {
func toSpace() -> MXSpace? {
guard let summary = self.summary, summary.roomType == .space else {
return nil
}
return MXSpace(roomId: self.roomId, session: self.mxSession)
}
}
| apache-2.0 |
Turistforeningen/SjekkUT | ios/SjekkUt/views/project/ProjectDatesCell.swift | 1 | 1578 | //
// StartStopCell.swift
// SjekkUt
//
// Created by Henrik Hartz on 31.03.2017.
// Copyright © 2017 Den Norske Turistforening. All rights reserved.
//
import Foundation
class ProjectDatesCell: UICollectionViewCell {
@IBOutlet var durationLabel: DntLabel!
let dateFormat = DateFormatter()
var project:Project? {
didSet {
dateFormat.dateStyle = .medium
dateFormat.timeStyle = .none
var durationText = ""
switch (project?.start, project?.stop) {
case (nil, nil):
durationText = "The list is always active"
case (nil, let stop):
let stopString = dateFormat.string(from: stop!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list is active until %@", comment: "list duration only stop"), stopString)
case (let start, nil):
let startString = dateFormat.string(from: start!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list active from %@", comment: "list duration only start"), startString)
case (let start, let stop):
let startString = dateFormat.string(from: start!)
let stopString = dateFormat.string(from: stop!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list is active in the period %@-%@", comment: "list duration start and stop"), startString, stopString)
}
durationLabel.text = durationText
}
}
}
| mit |
shitoudev/v2ex | v2exKit/STInsetLabel.swift | 1 | 939 | //
// STInsetLabel.swift
// v2ex
//
// Created by zhenwen on 7/31/15.
// Copyright (c) 2015 zhenwen. All rights reserved.
//
import UIKit
class STInsetLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) //UIEdgeInsetsZero
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
internal convenience init(frame: CGRect, inset:UIEdgeInsets) {
self.init(frame: frame)
self.padding = inset
}
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
}
override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.width += padding.left + padding.right
size.height += padding.top + padding.bottom
return size
}
} | mit |
benlangmuir/swift | test/SILGen/class_resilience.swift | 22 | 2399 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-emit-silgen -module-name class_resilience -I %t -enable-library-evolution %s | %FileCheck %s
import resilient_class
// Accessing final property of resilient class from different resilience domain
// through accessor
// CHECK-LABEL: sil [ossa] @$s16class_resilience20finalPropertyOfOtheryy010resilient_A022ResilientOutsideParentCF
// CHECK: function_ref @$s15resilient_class22ResilientOutsideParentC13finalPropertySSvg
public func finalPropertyOfOther(_ other: ResilientOutsideParent) {
_ = other.finalProperty
}
public class MyResilientClass {
public final var finalProperty: String = "MyResilientClass.finalProperty"
}
// Accessing final property of resilient class from my resilience domain
// directly
// CHECK-LABEL: sil [ossa] @$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $MyResilientClass):
// CHECK: ref_element_addr [[ARG]] : $MyResilientClass, #MyResilientClass.finalProperty
// CHECK: } // end sil function '$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF'
public func finalPropertyOfMine(_ other: MyResilientClass) {
_ = other.finalProperty
}
class SubclassOfOutsideChild : ResilientOutsideChild {
override func method() {}
func newMethod() {}
}
// Note: no entries for [inherited] methods
// CHECK-LABEL: sil_vtable SubclassOfOutsideChild {
// CHECK-NEXT: #ResilientOutsideParent.init!allocator: (ResilientOutsideParent.Type) -> () -> ResilientOutsideParent : @$s16class_resilience22SubclassOfOutsideChildCACycfC [override]
// CHECK-NEXT: #ResilientOutsideParent.method: (ResilientOutsideParent) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC6methodyyF [override]
// CHECK-NEXT: #SubclassOfOutsideChild.newMethod: (SubclassOfOutsideChild) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC9newMethodyyF
// CHECK-NEXT: #SubclassOfOutsideChild.deinit!deallocator: @$s16class_resilience22SubclassOfOutsideChildCfD
// CHECK-NEXT: }
| apache-2.0 |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/SearchEngines/OpenSearchEngine.swift | 2 | 7021 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
class OpenSearchEngine: NSObject, NSCoding {
struct UX {
static let preferredIconSize = 30
}
let shortName: String
let engineID: String?
let image: UIImage
let isCustomEngine: Bool
let searchTemplate: String
private let suggestTemplate: String?
private let searchTermComponent = "{searchTerms}"
private let localeTermComponent = "{moz:locale}"
private lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate()
private let googleEngineID = "google-b-1-m"
var headerSearchTitle: String {
guard engineID != googleEngineID else {
return .Search.GoogleEngineSectionTitle
}
return String(format: .Search.EngineSectionTitle, shortName)
}
enum CodingKeys: String, CodingKey {
case isCustomEngine
case searchTemplate
case shortName
case image
case engineID
}
init(engineID: String?,
shortName: String,
image: UIImage,
searchTemplate: String,
suggestTemplate: String?,
isCustomEngine: Bool) {
self.shortName = shortName
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
self.isCustomEngine = isCustomEngine
self.engineID = engineID
}
// MARK: - NSCoding
required init?(coder aDecoder: NSCoder) {
let isCustomEngine = aDecoder.decodeAsBool(forKey: CodingKeys.isCustomEngine.rawValue)
guard let searchTemplate = aDecoder.decodeObject(forKey: CodingKeys.searchTemplate.rawValue) as? String,
let shortName = aDecoder.decodeObject(forKey: CodingKeys.shortName.rawValue) as? String,
let image = aDecoder.decodeObject(forKey: CodingKeys.image.rawValue) as? UIImage else {
assertionFailure()
return nil
}
self.searchTemplate = searchTemplate
self.shortName = shortName
self.isCustomEngine = isCustomEngine
self.image = image
self.engineID = aDecoder.decodeObject(forKey: CodingKeys.engineID.rawValue) as? String
self.suggestTemplate = nil
}
func encode(with aCoder: NSCoder) {
aCoder.encode(searchTemplate, forKey: CodingKeys.searchTemplate.rawValue)
aCoder.encode(shortName, forKey: CodingKeys.shortName.rawValue)
aCoder.encode(isCustomEngine, forKey: CodingKeys.isCustomEngine.rawValue)
aCoder.encode(image, forKey: CodingKeys.image.rawValue)
aCoder.encode(engineID, forKey: CodingKeys.engineID.rawValue)
}
// MARK: - Public
/// Returns the search URL for the given query.
func searchURLForQuery(_ query: String) -> URL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/// Returns the search suggestion URL for the given query.
func suggestURLForQuery(_ query: String) -> URL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
/// Returns the query that was used to construct a given search URL
func queryForSearchURL(_ url: URL?) -> String? {
guard isSearchURLForEngine(url), let key = searchQueryComponentKey else { return nil }
if let value = url?.getQuery()[key] {
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
} else {
// If search term could not found in query, it may be exist inside fragment
var components = URLComponents()
components.query = url?.fragment?.removingPercentEncoding
guard let value = components.url?.getQuery()[key] else { return nil }
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
}
}
// MARK: - Private
/// Return the arg that we use for searching for this engine
/// Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this?
private func getQueryArgFromTemplate() -> String? {
// we have the replace the templates SearchTermComponent in order to make the template
// a valid URL, otherwise we cannot do the conversion to NSURLComponents
// and have to do flaky pattern matching instead.
let placeholder = "PLACEHOLDER"
let template = searchTemplate.replacingOccurrences(of: searchTermComponent, with: placeholder)
var components = URLComponents(string: template)
if let retVal = extractQueryArg(in: components?.queryItems, for: placeholder) {
return retVal
} else {
// Query arg may be exist inside fragment
components = URLComponents()
components?.query = URL(string: template)?.fragment
return extractQueryArg(in: components?.queryItems, for: placeholder)
}
}
private func extractQueryArg(in queryItems: [URLQueryItem]?, for placeholder: String) -> String? {
let searchTerm = queryItems?.filter { item in
return item.value == placeholder
}
return searchTerm?.first?.name
}
/// Check that the URL host contains the name of the search engine somewhere inside it
private func isSearchURLForEngine(_ url: URL?) -> Bool {
guard let urlHost = url?.shortDisplayString,
let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound,
let templateURL = URL(string: String(searchTemplate[..<queryEndIndex])) else { return false }
return urlHost == templateURL.shortDisplayString
}
private func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? {
if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: .SearchTermsAllowed) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnion(with: .URLAllowed)
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}"))
if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) {
let localeString = Locale.current.identifier
let urlString = encodedSearchTemplate
.replacingOccurrences(of: searchTermComponent, with: escapedQuery, options: .literal, range: nil)
.replacingOccurrences(of: localeTermComponent, with: localeString, options: .literal, range: nil)
return URL(string: urlString)
}
}
return nil
}
}
| mpl-2.0 |
sysatom/OSC | OSC/Logger.swift | 1 | 2359 | //
// Logger.swift
// OSC
//
// Created by yuan on 15/11/17.
// Copyright © 2015年 yuan. All rights reserved.
//
import UIKit
class Logger {
let destination: NSURL
lazy private var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
lazy private var fileHandle: NSFileHandle? = {
if let path = self.destination.path {
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
var error: NSError?
if let fileHandle = try? NSFileHandle(forWritingToURL: self.destination) {
print("Successfully logging to: \(path)")
return fileHandle
} else {
print("Serious error in logging: could not open path to log file. \(error).")
}
} else {
print("Serious error in logging: specified destination (\(self.destination)) does not appear to have a path component.")
}
return nil
}()
init(destination: NSURL) {
self.destination = destination
}
deinit {
fileHandle?.closeFile()
}
func log(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) {
let logMessage = stringRepresentation(message, function: function, file: file, line: line)
printToConsole(logMessage)
printToDestination(logMessage)
}
}
private extension Logger {
func stringRepresentation(message: String, function: String, file: String, line: Int) -> String {
let dateString = dateFormatter.stringFromDate(NSDate())
let file = NSURL(fileURLWithPath: file).lastPathComponent ?? "(Unknown File)"
return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
}
func printToConsole(logMessage: String) {
print(logMessage)
}
func printToDestination(logMessage: String) {
if let data = logMessage.dataUsingEncoding(NSUTF8StringEncoding) {
fileHandle?.writeData(data)
} else {
print("Serious error in logging: could not encode logged string into data.")
}
}
} | mit |
LucianoPolit/RepositoryKit | Example/Source/UserNetworkingRepository.swift | 1 | 1009 | //
// UserNetworkingRepository.swift
// Example
//
// Created by Luciano Polit on 3/11/16.
// Copyright © 2016 Luciano Polit. All rights reserved.
//
import RepositoryKit
// MARK: - User Repository (Networking)
/*
It needs to conform:
- RKCRUDNetworkingRepository: it is needed to manage CRUD operations on the networking store.
- RKDictionaryIdentifier: it is needed to be able to identify the entities with an id.
*/
class UserNetworkingRepository: CRUDNetworkingRepository, DictionaryIdentifier {
// MARK: - Typealiases
typealias Entity = [String: Any]
// MARK: - Properties
// The data store.
var store: Networking
// The path which identifies the repository on the store.
var path: String = "users"
// The key that is used to identify the user on the dictionary.
var identificationKey: String {
return "_id"
}
// MARK: - Initializers
init(store: Networking) {
self.store = store
}
}
| mit |
jrmsklar/SwiftPasscodeLock | PasscodeLock/PasscodeLockPresenter.swift | 1 | 4004 | //
// PasscodeLockPresenter.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/29/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
public class PasscodeLockPresenter {
private var mainWindow: UIWindow?
private lazy var passcodeLockWindow: UIWindow = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.windowLevel = 0
window.makeKeyAndVisible()
return window
}()
private let passcodeConfiguration: PasscodeLockConfigurationType
public var isPasscodePresented = false
public let passcodeLockVC: PasscodeLockViewController
public init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType, viewController: PasscodeLockViewController) {
mainWindow = window
mainWindow?.windowLevel = 1
passcodeConfiguration = configuration
passcodeLockVC = viewController
}
public convenience init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType) {
let passcodeLockVC = PasscodeLockViewController(state: .EnterPasscode, configuration: configuration)
self.init(mainWindow: window, configuration: configuration, viewController: passcodeLockVC)
}
// HACK: below function that handles not presenting the keyboard in case Passcode is presented
// is a smell in the code that had to be introduced for iOS9 where Apple decided to move the keyboard
// in a UIRemoteKeyboardWindow.
// This doesn't allow our Passcode Lock window to move on top of keyboard.
// Setting a higher windowLevel to our window or even trying to change keyboards'
// windowLevel has been tried without luck.
//
// Revise in a later version and remove the hack if not needed
func toggleKeyboardVisibility(hide hide: Bool) {
if let keyboardWindow = UIApplication.sharedApplication().windows.last
where keyboardWindow.description.hasPrefix("<UIRemoteKeyboardWindow")
{
keyboardWindow.alpha = hide ? 0.0 : 1.0
}
}
public func presentPasscodeLock() {
guard passcodeConfiguration.repository.hasPasscode else { return }
guard !isPasscodePresented else { return }
isPasscodePresented = true
passcodeLockWindow.windowLevel = 2
toggleKeyboardVisibility(hide: true)
let userDismissCompletionCallback = passcodeLockVC.dismissCompletionCallback
passcodeLockVC.dismissCompletionCallback = { [weak self] in
userDismissCompletionCallback?()
self?.dismissPasscodeLock()
}
passcodeLockWindow.rootViewController = passcodeLockVC
}
public func dismissPasscodeLock(animated animated: Bool = true) {
isPasscodePresented = false
mainWindow?.windowLevel = 1
mainWindow?.makeKeyAndVisible()
if animated {
UIView.animateWithDuration(
0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [.CurveEaseInOut],
animations: { [weak self] in
self?.passcodeLockWindow.alpha = 0
},
completion: { [weak self] _ in
self?.passcodeLockWindow.windowLevel = 0
self?.passcodeLockWindow.rootViewController = nil
self?.passcodeLockWindow.alpha = 1
self?.toggleKeyboardVisibility(hide: false)
}
)
} else {
passcodeLockWindow.windowLevel = 0
passcodeLockWindow.rootViewController = nil
toggleKeyboardVisibility(hide: false)
}
}
}
| mit |
gregomni/swift | test/Generics/concrete_conformances_in_protocol.swift | 2 | 1938 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// rdar://problem/88135912
// XFAIL: *
protocol P {
associatedtype T
}
struct S : P {
typealias T = S
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R0@
// CHECK-LABEL: Requirement signature: <Self where Self.[R0]A == S>
protocol R0 {
associatedtype A where A : P, A == S
}
////
struct G<T> : P {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R1@
// CHECK-LABEL: Requirement signature: <Self where Self.[R1]B == G<Self.[R1]A>>
protocol R1 {
associatedtype A
associatedtype B where B : P, B == G<A>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R2@
// CHECK-LABEL: Requirement signature: <Self where Self.[R2]A == G<Self.[R2]B>>
protocol R2 {
associatedtype A where A : P, A == G<B>
associatedtype B
}
////
protocol PP {
associatedtype T : P
}
struct GG<T : P> : PP {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR3@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR3]A : P, Self.[RR3]B == GG<Self.[RR3]A>>
protocol RR3 {
associatedtype A : P
associatedtype B where B : PP, B == GG<A>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR4@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR4]A == GG<Self.[RR4]B>, Self.[RR4]B : P>
protocol RR4 {
associatedtype A where A : PP, A == GG<B>
associatedtype B : P
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR5@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR5]A : PP, Self.[RR5]B == GG<Self.[RR5]A.[PP]T>>
protocol RR5 {
associatedtype A : PP
associatedtype B where B : PP, B == GG<A.T>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR6@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR6]A == GG<Self.[RR6]B.[PP]T>, Self.[RR6]B : PP>
protocol RR6 {
associatedtype A where A : PP, A == GG<B.T>
associatedtype B : PP
}
| apache-2.0 |
gregomni/swift | test/Interop/Cxx/namespace/classes-module-interface.swift | 8 | 2340 | // RUN: %target-swift-ide-test -print-module -module-to-print=Classes -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: enum ClassesNS1 {
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS2 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS3 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias GlobalAliasToNS1 = ClassesNS1
// CHECK-NEXT: enum ClassesNS4 {
// CHECK-NEXT: typealias AliasToGlobalNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasToGlobalNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToInnerNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: typealias AliasToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: typealias AliasChainToNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasChainToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToAnotherNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToNS5NS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToGlobalNS5 = ClassesNS5
// CHECK-NEXT: typealias AliasToLocalNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: typealias AliasToNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
| apache-2.0 |
fcanas/Formulary | Formulary/Forms/FormViewController.swift | 1 | 10306 | //
// FormViewController.swift
// Formulary
//
// Created by Fabian Canas on 1/16/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import UIKit
/**
* `FormViewController` is a descendent of `UIViewController` used to display
* a `Form` in a UIKit application.
*
* In order to show a `Form` to a user, you will typically create a `Form`,
* instantiate a `FormViewController`, set the `FormViewController`'s `form`
* property, and present the `FormViewController`.
*
* Where a `Form` refers to both the schema and data an application wishes to
* obtain from a user, the `FormViewController` is an adapter that manages the
* visual presentation of a `Form`, manages the lifecycle of interaction with
* the `Form`, and is a key point of interaction with the rest of an iOS
* application.
*
* - seealso: `Form`
*/
open class FormViewController: UIViewController {
fileprivate var dataSource: FormDataSource?
/**
* The `Form` that the `FormViewController` presents to the user
*
* - seealso: `Form`
*/
open var form :Form {
didSet {
form.editingEnabled = editingEnabled
dataSource = FormDataSource(form: form, tableView: tableView)
tableView?.dataSource = dataSource
}
}
/**
* The UITableView instance the `FormViewController` will populate with
* `Form` data.
*
* If this property is `nil` when `viewDidLoad` is called, the
* `FormViewController` will create a `UITableView` and add it to its view
* hierarchy.
*/
open var tableView: UITableView!
/**
* The style of `tableView` to create in `viewDidLoad` if no `tableView`
* exists.
*
* Setting `tableViewStyle` only has an effect if set before `viewDidLoad`
* is called and the `FormViewController` does not yet have a `tableView`.
* Otherwise its value is never read.
*
* - seealso: tableView
*/
open var tableViewStyle: UITableViewStyle = .grouped
/**
* Enables or disables editing of the represented `Form`.
*/
open var editingEnabled :Bool = true {
didSet {
self.form.editingEnabled = editingEnabled
if isEditing == false {
self.tableView?.firstResponder()?.resignFirstResponder()
}
self.tableView?.reloadData()
}
}
lazy fileprivate var tableViewDelegate :FormViewControllerTableDelegate = {
return FormViewControllerTableDelegate(formViewController: self)
}()
/**
* Returns a newly initialized form view controller with the nib file in the
* specified bundle and ready to represent the specified Form.
*
* - parameters:
* - form: The Form to show in the FormViewController
* - nibName: The name of the nib file to associate with the view controller. The nib file name should not contain any leading path information. If you specify nil, the nibName property is set to nil.
* - nibBundle: The bundle in which to search for the nib file. This method looks for the nib file in the bundle's language-specific project directories first, followed by the Resources directory. If this parameter is nil, the method uses the heuristics described below to locate the nib file.
*/
public init(form: Form = Form(sections: []), nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.form = form
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
* Returns a newly initialized FormViewController with a Form
*
* - parameter: form The Form to show in the FormViewController
*/
public convenience init(form: Form) {
self.init(form: form, nibName: nil, bundle: nil)
}
/**
* Returns a newly initialized FormViewController with an empty Form.
*
* Use this convenience initializer for compatibility with generic UIKit
* view controllers. It is perfectly acceptable to create a Form and assign
* it to the FormViewController after initialization.
*/
public override convenience init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.init(form: Form(sections: []), nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
* Returns a newly initialized FormViewController with an empty Form.
*
* Use this convenience initializer for compatibility with generic UIKit
* view controllers. It is perfectly acceptable to create a Form and assign
* it to the FormViewController after initialization.
*/
public required init?(coder aDecoder: NSCoder) {
form = Form(sections: [])
super.init(coder: aDecoder)
}
fileprivate func link(_ form: Form, table: UITableView) {
dataSource = FormDataSource(form: form, tableView: tableView)
tableView.dataSource = dataSource
}
/**
* Called by UIKit after the controller's view is loaded into memory.
*
* FormViewController implements custom logic to ensure that a Form can be
* correctly displayed regarless of how it was constructed. This includes
* creating and configuring a Table View and constructing a private data
* source for the table view.
*
* You typically will not need to override -viewDidLoad in subclasses of
* FormViewController. But if you do, things will work better if you invoke
* the superclass's implementation first.
*/
override open func viewDidLoad() {
super.viewDidLoad()
if tableView == nil {
tableView = UITableView(frame: view.bounds, style: tableViewStyle)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
if tableView.superview == nil {
view.addSubview(tableView)
}
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 60
tableView.delegate = tableViewDelegate
dataSource = FormDataSource(form: form, tableView: tableView)
tableView.dataSource = dataSource
}
/**
* If you override this method, you must call super at some point in your
* implementation.
*/
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
/**
* If you override this method, you must call super at some point in your
* implementation.
*/
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
}
private extension FormViewController {
@objc func keyboardWillShow(_ notification: Notification) {
if let cell = tableView.firstResponder()?.containingCell(),
let selectedIndexPath = tableView.indexPath(for: cell) {
let keyboardInfo = KeyboardNotification(notification)
var keyboardEndFrame = keyboardInfo.screenFrameEnd
keyboardEndFrame = view.window!.convert(keyboardEndFrame, to: view)
var contentInset = tableView.contentInset
var scrollIndicatorInsets = tableView.scrollIndicatorInsets
contentInset.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y
scrollIndicatorInsets.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y
UIView.beginAnimations("keyboardAnimation", context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .easeInOut)
UIView.setAnimationDuration(keyboardInfo.animationDuration)
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = scrollIndicatorInsets
tableView.scrollToRow(at: selectedIndexPath, at: .none, animated: true)
UIView.commitAnimations()
}
}
@objc func keyboardWillHide(_ notification: Notification) {
let keyboardInfo = KeyboardNotification(notification)
var contentInset = tableView.contentInset
var scrollIndicatorInsets = tableView.scrollIndicatorInsets
contentInset.bottom = 0
scrollIndicatorInsets.bottom = 0
UIView.beginAnimations("keyboardAnimation", context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .easeInOut)
UIView.setAnimationDuration(keyboardInfo.animationDuration)
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = scrollIndicatorInsets
UIView.commitAnimations()
}
}
private class FormViewControllerTableDelegate :NSObject, UITableViewDelegate {
weak var formViewController :FormViewController?
init(formViewController :FormViewController) {
super.init()
self.formViewController = formViewController
}
@objc func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
formViewController?.tableView.firstResponder()?.resignFirstResponder()
}
@objc func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if let cell = cell as? FormTableViewCell {
cell.formRow?.action?(nil)
cell.action?(nil)
}
if let cell = cell as? ControllerSpringingCell, let controller = cell.nestedViewController {
formViewController?.navigationController?.pushViewController(controller(), animated: true)
}
}
}
| mit |
DylanVann/DatePickerCell | Example/AppDelegate.swift | 1 | 2172 | //
// AppDelegate.swift
// Example
//
// Created by Dylan Vann on 2015-05-12.
// Copyright (c) 2015 Dylan Vann. All rights reserved.
//
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
}
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:.
}
}
| mit |
zning1994/practice | Swift学习/code4xcode6/ch11/11.6.2可选链3.playground/section-1.swift | 1 | 725 | // 本书网站:http://www.51work6.com/swift.php
// 智捷iOS课堂在线课堂:http://v.51work6.com
// 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973
// 智捷iOS课堂微信公共账号:智捷iOS课堂
// 作者微博:http://weibo.com/516inc
// 官方csdn博客:http://blog.csdn.net/tonny_guan
// Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:jylong06@163.com
class Employee {
var no : Int = 0
var name : String = ""
var job : String = ""
var salary : Double = 0
var dept : Department? = Department()
struct Department {
var no : Int = 10
var name : String = "SALES"
}
}
var emp = Employee()
println(emp.dept?.name)
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.