hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
f782c16600b542a58234a9fd918a7132f448b423 | 377 | //
// Chat.swift
// Hahabbit
//
// Created by TSAI TSUNG-HAN on 2021/5/30.
//
import Foundation
struct Chat {
var users: [String]
var dictionary: [String: Any] {
return ["users": users]
}
}
extension Chat {
init?(dictionary: [String: Any]) {
guard let chatUsers = dictionary["users"] as? [String] else { return nil }
self.init(users: chatUsers)
}
}
| 16.391304 | 78 | 0.625995 |
d6fe5329998b8d35418aa7db4d3b7af2e60aafc8 | 584 | //
// AASupportedCapability+Extensions.swift
// Car
//
// Created by Mikk Rätsep on 10.01.20.
// Copyright © 2020 High-Mobility GmbH. All rights reserved.
//
import AutoAPI
import Foundation
extension AASupportedCapability {
public func supports(propertyIDs: UInt8...) -> Bool {
Set(supportedPropertyIDs).isSuperset(of: propertyIDs)
}
public func supportsAllProperties<C: CaseIterable & RawRepresentable>(for capability: C.Type) -> Bool where C.RawValue == UInt8 {
Set(supportedPropertyIDs) == Set(capability.allCases.map { $0.rawValue })
}
}
| 25.391304 | 133 | 0.705479 |
6a6c9cafaf4079b35aada4cce9b0529e3e9bc5f4 | 2,039 | //
// SplitView.swift
// GitBlamePR
//
// Created by Makoto Aoyama on 2020/03/28.
// Copyright © 2020 dev.aoyama. All rights reserved.
//
import SwiftUI
struct SplitView<Master, Detail>: View where Master : View, Detail : View {
var master: Master
var detail: Detail
@State private var detailWidth: CGFloat = 250
@State private var detailWidthOfDraggOnEnd: CGFloat = 250
let detailWidthMin: CGFloat = 160
private var drag: some Gesture {
DragGesture(minimumDistance: 1, coordinateSpace: .global)
.onChanged { value in
self.detailWidth = max(self.detailWidthOfDraggOnEnd - value.translation.width, self.detailWidthMin)
self.applyCoursor(dragging: true)
}.onEnded { (value) in
self.detailWidthOfDraggOnEnd = max(self.detailWidthOfDraggOnEnd - value.translation.width, self.detailWidthMin)
self.applyCoursor(dragging: false)
}
}
var body: some View {
HStack(spacing: 0) {
master
SplitSeparator().frame(width: 1).gesture(drag).onHover { (enters) in
if enters {
self.applyCoursor(dragging: true)
} else {
self.applyCoursor(dragging: false)
}
}
detail.frame(width: detailWidth)
}
}
private func applyCoursor(dragging: Bool) {
guard dragging else {
NSCursor.arrow.set()
return
}
if self.detailWidth == self.detailWidthMin {
NSCursor.resizeLeft.set()
} else {
NSCursor.resizeLeftRight.set()
}
}
}
struct SplitView_Previews: PreviewProvider {
static var previews: some View {
Group {
SplitView(master: Text("Master"), detail: Text("Detail"))
SplitView(master: Text("Master"), detail: Text("Detail")).background(Color(.textBackgroundColor))
.environment(\.colorScheme, .dark)
}
}
}
| 30.893939 | 127 | 0.587052 |
5b26a6ded32bb69fe795a5341a06368efb3b5457 | 1,759 | //
// File.swift
// File
//
// Created by Mahadevaiah, Pavan | Pavan | ECMPD on 2021/08/27.
//
import Foundation
@resultBuilder
public struct RRequestBuilder {
/// Required by every result builder to build combined results from
/// statement blocks.
public static func buildBlock(_ params: RequestParameter...) -> RequestParameter {
CombinedParameters(params)
}
/// Required by every result builder to build combined results from
/// statement blocks.
public static func buildBlock(_ param: RequestParameter) -> RequestParameter {
param
}
/// Required by every result builder to build combined results from
/// statement blocks.
public static func buildBlock() -> EmptyParameter {
EmptyParameter()
}
/// Enables support for `if` statements that do not have an `else`.
public static func buildOptional(_ param: RequestParameter?) -> RequestParameter {
param ?? EmptyParameter()
}
/// With buildEither(second:), enables support for 'if-else' and 'switch'
/// statements by folding conditional results into a single result.
public static func buildEither(first: RequestParameter) -> RequestParameter {
first
}
/// With buildEither(second:), enables support for 'if-else' and 'switch'
/// statements by folding conditional results into a single result.
public static func buildEither(second: RequestParameter) -> RequestParameter {
second
}
/// Enables support for 'for..in' loops by combining the
/// results of all iterations into a single result.
public static func buildArray(_ params: [RequestParameter]) -> RequestParameter {
CombinedParameters(params)
}
}
| 32.574074 | 86 | 0.676521 |
61641ea0e9fc5703a075f5622471fdb825858600 | 2,165 | /***************************************************************************
* Copyright 2018-2019 alladin-IT GmbH
*
* 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
///
enum TaskType: String, Codable {
///
case tcpPort = "tcp"
///
case udpPort = "udp"
///
case echoProtocol = "echo_protocol"
///
case dns = "dns"
///
case httpProxy = "http_proxy"
///
case nonTransparentProxy = "non_transparent_proxy"
///
case traceroute = "traceroute"
///
case website = "website"
///
case voip = "voip"
///
case sip = "sip"
///
case mkitWebConnectivity = "mkit_web_connectivity"
///
case mkitDash = "mkit_dash"
///
func taskClass() -> QoSTask.Type {
switch self {
case .tcpPort:
return TcpPortTask.self
case .udpPort:
return UdpPortTask.self
case .echoProtocol:
return EchoProtocolTask.self
case .dns:
return DnsTask.self
case .httpProxy:
return HttpProxyTask.self
case .nonTransparentProxy:
return NonTransparentProxyTask.self
case .traceroute:
return TracerouteTask.self
case .website:
return WebsiteRenderingTask.self
case .voip:
return VoipTask.self
case .sip:
return SipTask.self
case .mkitWebConnectivity:
return MeasurementKitTask.self
case .mkitDash:
return MeasurementKitTask.self
}
}
}
| 24.325843 | 77 | 0.566282 |
03b0a9baf268540d5d69d81ab62580e37ed56760 | 2,340 | //
// AutoSyncFrequency.swift
// FitDataProtocol
//
// Created by Kevin Hoogheem on 12/15/19.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// FIT Auto Sync Frequency
public enum AutoSyncFrequency: UInt8 {
/// Never
case never = 0
/// Occasionally
case occasionally = 1
/// Frequent
case frequent = 2
/// Once a Day
case onceDay = 3
/// Remote
case remote = 4
/// Invalid
case invalid = 255
}
// MARK: - FitFieldCodeable
extension AutoSyncFrequency: FitFieldCodeable {
/// Encode Into Data
/// - Parameter base: BaseTypeData
public func encode(base: BaseTypeData) -> Data? {
Data(from: self.rawValue.littleEndian)
}
/// Decode FIT Field
///
/// - Parameters:
/// - type: Type of Field
/// - data: Data to Decode
/// - base: BaseTypeData
/// - arch: Endian
/// - Returns: Decoded Value
public static func decode<T>(type: T.Type, data: Data, base: BaseTypeData, arch: Endian) -> T? {
if let value = base.type.decode(type: UInt8.self, data: data, resolution: base.resolution, arch: arch) {
return AutoSyncFrequency(rawValue: value) as? T
}
return nil
}
}
| 33.913043 | 112 | 0.660256 |
fc65ae19027fa04d177cd46d7241d66da4ab6480 | 964 | //
// CoreDishRecipe+CoreDataClass.swift
// GoldenDish
//
// Created by נדב אבנון on 22/02/2021.
//
//
import Foundation
import CoreData
@objc(CoreHotFavoriteRecipe)
public class CoreHotFavoriteRecipe: NSManagedObject {
convenience init(dishId:Int64,title:String, readyInMinutes: Int64, imageUrl: String, glutenFree:Bool, vegan:Bool, vegetarian:Bool, veryHealthy:Bool, veryPopular:Bool,ingrediants:NSArray,instructions:String) {
self.init(context:CoreData.shared.persistentContainer.viewContext)
self.dishId = dishId
self.title = title
self.readyInMinutes = readyInMinutes
self.imageUrl = imageUrl
self.glutenFree = glutenFree
self.vegan = vegan
self.vegetarian = vegetarian
self.veryHealthy = veryHealthy
self.veryPopular = veryPopular
self.ingrediants = ingrediants
self.instructions = instructions
self.rand = Int64.random(in: 1..<9000000)
}
}
| 32.133333 | 212 | 0.707469 |
dd447f62c23554862ed61ae54807adb8c31cd4ee | 501 | import SwiftUI
public struct IconPreviews<Icon: View>: View {
public var icon: Icon
public var configs: [IconConfig]
public var clip: Bool
public init(icon: Icon, configs: [IconConfig], clip: Bool = true) {
self.icon = icon
self.configs = configs
self.clip = clip
}
public var body: some View {
VStack(alignment: .leading, spacing: 16) {
ForEach(configs) { config in
IconPreview(icon: icon, config: config, clip: clip)
}
}
.fixedSize()
}
}
| 21.782609 | 69 | 0.638723 |
e96d3b73fa7ce3b477db934ebdf866782ec53d9f | 3,241 | //
// ReviewListViewController.swift
// YuePeiYang
//
// Created by Halcao on 2016/10/23.
// Copyright © 2016年 Halcao. All rights reserved.
//
import UIKit
class ReviewListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var reviewArr: [Review] = []
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) , style: .Grouped)
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let titleLabel = UILabel(text: "我的评论", fontSize: 17)
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.textAlignment = .Center
titleLabel.textColor = UIColor.whiteColor()
self.navigationItem.titleView = titleLabel;
//NavigationBar 的背景,使用了View
self.navigationController!.jz_navigationBarBackgroundAlpha = 0;
let bgView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height))
bgView.backgroundColor = UIColor(colorLiteralRed: 234.0/255.0, green: 74.0/255.0, blue: 70/255.0, alpha: 1.0)
self.view.addSubview(bgView)
// //改变 statusBar 颜色
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true)
if self.reviewArr.count == 0 {
let label = UILabel(text: "你还没有点评哦,去评论吧!")
label.sizeToFit()
self.view.addSubview(label)
label.snp_makeConstraints { make in
make.center.equalTo(self.view.snp_center)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Add TableView
view.addSubview(tableView)
self.tableView.delegate = self
self.tableView.dataSource = self
//self.tableView.tableFooterView = UIView()
self.tableView.estimatedRowHeight = 130
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.separatorStyle = .None
}
// Mark: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reviewArr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ReviewCell(model: self.reviewArr[indexPath.row])
if indexPath.row == reviewArr.count - 1 {
cell.separator.removeFromSuperview()
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = BookDetailViewController(bookID: "\(reviewArr[indexPath.row].bookID)")
self.navigationController?.pushViewController(vc, animated: true)
print("Push Detail View Controller, bookID: \(reviewArr[indexPath.row].bookID)")
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} | 38.129412 | 218 | 0.659981 |
5d3f0c87dba6d8bd96cd460366bd3c223acfe14b | 2,000 | import EmceeExtensions
import Foundation
import Kibana
import Logging
import MetricsExtensions
public final class KibanaLoggerHandler: LoggerHandler {
private let group = DispatchGroup()
private let kibanaClient: KibanaClient
public static let skipMetadataFlag = "skipKibana"
public init(kibanaClient: KibanaClient) {
self.kibanaClient = kibanaClient
}
public func handle(logEntry: LogEntry) {
// no-op and should not be used.
}
public func tearDownLogging(timeout: TimeInterval) {
_ = group.wait(timeout: .now() + timeout)
}
public func log(
level: Logging.Logger.Level,
message: Logging.Logger.Message,
metadata: Logging.Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
guard metadata?[Self.skipMetadataFlag] == nil else { return }
var kibanaPayload = [
"fileLine": "\(file.lastPathComponent):\(line)",
]
for keyValue in metadata ?? [:] {
switch keyValue.value {
case let .string(value):
kibanaPayload[keyValue.key] = value
case let .stringConvertible(value):
kibanaPayload[keyValue.key] = value.description
case .array, .dictionary:
break
}
}
do {
group.enter()
try kibanaClient.send(
level: level.rawValue,
message: message.description,
metadata: kibanaPayload
) { [group] _ in
group.leave()
}
} catch {
group.leave()
}
}
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
get { nil }
set(newValue) {}
}
public var metadata: Logging.Logger.Metadata = [:]
public var logLevel: Logging.Logger.Level = .debug
}
| 27.39726 | 79 | 0.558 |
61ada86d215880fcd0a1a6241107c622a02f27e4 | 974 | //
// MQDouYuTVTests.swift
// MQDouYuTVTests
//
// Created by mengmeng on 16/9/21.
// Copyright © 2016年 mengQuietly. All rights reserved.
//
import XCTest
@testable import MQDouYuTV
class MQDouYuTVTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.324324 | 111 | 0.635524 |
8a5cba1ace21541e6b5d45a13e9dd79f7b6faf90 | 745 | //
// AppDelegate.swift
// KenticoCloud
//
// Created by [email protected] on 08/16/2017.
// Copyright © 2017 Kentico Software. All rights reserved.
//
import UIKit
import KenticoCloud
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Customize appearance
UINavigationBar.appearance().isHidden = true
UITableView.appearance().backgroundColor = AppConstants.globalBackgroundColor
UITableViewCell.appearance().backgroundColor = AppConstants.globalBackgroundColor
return true
}
}
| 27.592593 | 144 | 0.739597 |
7626827d1ef7b70f6113fcc1f0df829b3786a353 | 4,670 | import Foundation
/// Execution Context
///
/// Defines a context for operations to be performed in.
/// e.g. `.concurrent` or `.serial`
///
public struct ExecutionContext {
public enum ExecutionType {
case serial
case concurrent
}
public var executionType: ExecutionType
public init(executionType: ExecutionType) {
self.executionType = executionType
}
public static var serial: ExecutionContext {
ExecutionContext(executionType: .serial)
}
public static var concurrent: ExecutionContext {
ExecutionContext(executionType: .concurrent)
}
}
public extension Array {
/// Map (with execution context)
///
/// - Parameters:
/// - context: The execution context to perform the `transform` with
/// - transform: The transformation closure to apply to the array
func map<B>(context: ExecutionContext, _ transform: (Element) throws -> B) rethrows -> [B] {
switch context.executionType {
case .serial:
return try map(transform)
case .concurrent:
return try concurrentMap(transform)
}
}
/// Compact map (with execution context)
///
/// - Parameters:
/// - context: The execution context to perform the `transform` with
/// - transform: The transformation closure to apply to the array
func compactMap<B>(context: ExecutionContext, _ transform: (Element) throws -> B?) rethrows -> [B] {
switch context.executionType {
case .serial:
return try compactMap(transform)
case .concurrent:
return try concurrentCompactMap(transform)
}
}
/// For Each (with execution context)
///
/// - Parameters:
/// - context: The execution context to perform the `perform` operation with
/// - transform: The perform closure to call on each element in the array
func forEach(context: ExecutionContext, _ perform: (Element) throws -> Void) rethrows {
switch context.executionType {
case .serial:
return try forEach(perform)
case .concurrent:
return try concurrentForEach(perform)
}
}
}
// MARK: - Private
//
// Concurrent Map / For Each
// based on https://talk.objc.io/episodes/S01E90-concurrent-map
//
extension Array {
private final class ThreadSafe<A> {
private var _value: A
private let queue = DispatchQueue(label: "ThreadSafe")
init(_ value: A) {
_value = value
}
var value: A {
queue.sync { _value }
}
func atomically(_ transform: @escaping (inout A) -> Void) {
queue.async {
transform(&self._value)
}
}
}
private func concurrentMap<B>(_ transform: (Element) throws -> B) rethrows -> [B] {
let result = ThreadSafe([Result<B, Error>?](repeating: nil, count: count))
DispatchQueue.concurrentPerform(iterations: count) { idx in
let element = self[idx]
do {
let transformed = try transform(element)
result.atomically {
$0[idx] = .success(transformed)
}
} catch {
result.atomically {
$0[idx] = .failure(error)
}
}
}
return try result.value.map { try $0!.get() }
}
private func concurrentCompactMap<B>(_ transform: (Element) throws -> B?) rethrows -> [B] {
let result = ThreadSafe([Result<B, Error>?](repeating: nil, count: count))
DispatchQueue.concurrentPerform(iterations: count) { idx in
let element = self[idx]
do {
guard let transformed = try transform(element) else { return }
result.atomically {
$0[idx] = .success(transformed)
}
} catch {
result.atomically {
$0[idx] = .failure(error)
}
}
}
return try result.value.map { try $0!.get() }
}
private func concurrentForEach(_ perform: (Element) throws -> Void) rethrows {
let result = ThreadSafe([Error?](repeating: nil, count: count))
DispatchQueue.concurrentPerform(iterations: count) { idx in
let element = self[idx]
do {
try perform(element)
} catch {
result.atomically {
$0[idx] = error
}
}
}
return try result.value.compactMap { $0 }.forEach {
throw $0
}
}
}
| 31.133333 | 104 | 0.5606 |
e27aaf828e74c7691e66fa2e415cc68bd02e6076 | 3,884 | //
// SKPreOrderDFSIteratorTests.swift
// Sylvester Tests 😼
//
// Created by Chris Zielinski on 12/4/18.
// Copyright © 2018 Big Z Labs. All rights reserved.
//
import XCTest
#if XPC
@testable import SylvesterXPC
#else
@testable import Sylvester
#endif
class SKPreOrderDFSIteratorTests: SylvesterMockEditorOpenTestCase {
// MARK: - Test Declarations
class FunctionIterator<Substructure: CustomSubstructure>: SKPreOrderDFSIterator<Substructure> {
override func next() -> Substructure? {
guard let nextSubstructure = super.next()
else { return nil }
if nextSubstructure.isFunction {
return nextSubstructure
} else {
return next()
}
}
}
final class CustomSubstructure: SKBaseSubstructure, SKFinalSubclass {
override class func iteratorClass<Substructure: CustomSubstructure>()
-> SKPreOrderDFSIterator<Substructure>.Type {
return FunctionIterator.self
}
override func decodeChildren(from container: DecodingContainer) throws -> [SKBaseSubstructure]? {
return try decodeChildren(CustomSubstructure.self, from: container)
}
}
// MARK: - Stored Properties
let preOrderDFSViewControllerEditorOpenNames = [
"ViewController",
"viewDidLoad()",
"super.viewDidLoad",
"String",
"contentsOf",
"URL",
"fileURLWithPath",
"genericFunction(with:)",
"T",
"parameter"
]
let preOrderDFSViewControllerDocInfoNames = [
"ViewController",
"viewDidLoad()",
"genericFunction(with:)",
"parameter"
]
// MARK: - Test Methods
func testViewControllerEditorOpenOrder() {
continueAfterFailure = false
var count = 0
for (index, substructure) in viewControllerEditorOpenResponse.topLevelSubstructures.enumerated() {
XCTAssertEqual(index, count,
"the enumerated index is not equal to the count")
XCTAssertEqual(index, substructure.index,
"substructure has incorrect index")
XCTAssertLessThan(index, preOrderDFSViewControllerEditorOpenNames.count,
"response contains more substructures than the test expects")
XCTAssertEqual(substructure.name, preOrderDFSViewControllerEditorOpenNames[index],
"`SKPreOrderDFSIterator` is not pre-order DFS")
count += 1
}
XCTAssertEqual(count, preOrderDFSViewControllerEditorOpenNames.count)
}
func testViewControllerDocInfoOrder() {
continueAfterFailure = false
var count = 0
for (index, entity) in viewControllerDocInfoResponse.topLevelEntities!.enumerated() {
XCTAssertEqual(index, count,
"the enumerated index is not equal to the count")
XCTAssertEqual(index, entity.index,
"the entity has incorrect index")
XCTAssertLessThan(index, preOrderDFSViewControllerDocInfoNames.count,
"the response contains more entities than the test expects")
XCTAssertEqual(entity.name, preOrderDFSViewControllerDocInfoNames[index],
"`SKPreOrderDFSIterator` is not pre-order DFS")
count += 1
}
XCTAssertEqual(count, preOrderDFSViewControllerDocInfoNames.count)
}
func testSubstructureSubclassIterator() throws {
let customEditorOpen = try SKGenericEditorOpen<CustomSubstructure>(file: viewControllerFile)
let functionCount = customEditorOpen.topLevelSubstructures.reduce(0) { (count, _) in return count + 1 }
XCTAssertEqual(functionCount, 2)
}
}
| 33.773913 | 111 | 0.628991 |
71db3f1d3079d537ce5872ea3ab945b79c3ec5ae | 2,225 | //
// CollectBottomDeleteView.swift
// PSTodayNews
//
// Created by 思 彭 on 2017/5/25.
// Copyright © 2017年 思 彭. All rights reserved.
//
import UIKit
import SnapKit
typealias AllDeleteClosure = (() -> Void)
typealias DeleteClosure = (() -> Void)
class CollectBottomDeleteView: UIView {
var allDeleteClosure: AllDeleteClosure? = nil
var deleteClosure: DeleteClosure? = nil
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
layOut()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
self.addSubview(allDeleteButton)
self.addSubview(deleteButton)
}
func layOut() {
allDeleteButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.centerY.equalTo(self)
make.width.equalTo(100)
make.height.equalTo(self)
}
deleteButton.snp.makeConstraints { (make) in
make.right.equalTo(self).offset(-10)
make.centerY.equalTo(self)
make.width.equalTo(50)
make.height.equalTo(self)
}
}
// 懒加载
lazy var allDeleteButton: UIButton = {
let button = UIButton()
button.setTitle("一键清空", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.setTitleColor(UIColor.gray, for: .normal)
button.addTarget(self, action: #selector(allDeleteAction), for: .touchUpInside)
return button
}()
lazy var deleteButton: UIButton = {
let button = UIButton()
button.setTitle("删除", for: .normal)
button.isSelected = false
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.setTitleColor(UIColor.gray, for: .normal)
button.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
return button
}()
func allDeleteAction() {
if allDeleteClosure != nil {
allDeleteClosure!()
}
}
func deleteAction() {
if deleteClosure != nil {
deleteClosure!()
}
}
}
| 26.488095 | 87 | 0.591461 |
4a4fb983287f8350e27b2145bdebc1c4bb6ec765 | 288 | //
// ViewController.swift
// UrsusSigilTestApp
//
// Created by Nicholas Arner on 11/30/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 14.4 | 58 | 0.659722 |
79569340220ed979ce5b696ac96051239dd91f82 | 1,138 | //
// SRPinUITests.swift
// SRPinUITests
//
// Created by 黄彦棋 on 2019/3/7.
// Copyright © 2019 Seer. All rights reserved.
//
import XCTest
class SRPinUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 32.514286 | 182 | 0.685413 |
23ddfaa8dfc4ca69e763d04a86f8ce2465af7c2c | 1,432 | //
// User.swift
// Parsetagram
//
// Created by Meena Sengottuvelu on 6/22/16.
// Copyright © 2016 Meena Sengottuvelu. All rights reserved.
//
import UIKit
import Parse
public class User: PFUser {
private var profilePicURLVar: NSURL?;
var profilePicURL: NSURL? {
get {
if(profilePicURLVar == nil) {
let file = objectForKey("profilePicture") as? PFFile;
let url = Post.getURLFromFile(file!);
profilePicURLVar = NSURL(string: url);
}
return profilePicURLVar;
}
set {
profilePicURLVar = profilePicURL;
}
}
var postsCount: Int? {
let query = PFQuery(className: "Post");
query.whereKey("author", equalTo: self);
return query.countObjects(nil);
}
public func posts(offset: Int = 0, limit: Int = 20, completion: PFQueryArrayResultBlock) -> [Post]? {
return Post.fetchPosts(offset, limit: limit, authorConstraint: self, completion: completion);
}
public class func getUserByUsername(username: String) -> User {
let query = PFUser.query();
query?.whereKey("username", equalTo: username);
var result: PFObject?;
do {
result = try query!.getFirstObject();
} catch(_) {
}
return result as! User;
}
}
| 26.036364 | 105 | 0.555866 |
b94b8423213e37b79cd022082d9cc70fd916ec93 | 7,604 | import UIKit
import FlexLayout
final class CWAlertView: CWBaseAlertView {
private(set) var innerView: UIView?
var messageLabel: UILabel? {
return innerView as? UILabel
}
let actionsStackView: UIStackView
let separatorView: UIView
private(set) var activityIndicatorView: UIActivityIndicatorView?
required init() {
actionsStackView = UIStackView(arrangedSubviews: [])
separatorView = UIView()
super.init()
}
override func configureView() {
super.configureView()
// isOpaque = true
// rootFlexContainer.backgroundColor = UIColor.whiteSmoke.withAlphaComponent(0.4)
// contentView.layer.masksToBounds = false
// titleLabel.textAlignment = .center
// titleLabel.numberOfLines = 0
// titleLabel.textColor = UIColor.blueBolt
// contentView.layer.shadowRadius = 20
// contentView.layer.shadowOffset = CGSize(width: 2, height: 1)
// contentView.layer.shadowOpacity = 0.3
// contentView.layer.shadowColor = UIColor.lightGray.cgColor
// actionsStackView.distribution = .fill
// actionsStackView.alignment = .fill
separatorView.isHidden = true
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.layer.cornerRadius = contentView.frame.size.height * 0.1
}
override func configureConstraints() {
contentView.flex.backgroundColor(Theme.current.container.background).alignItems(.center).define { flex in
flex.addItem(statusImageView).width(100).height(100).alignSelf(.center).position(.absolute).top(-30)
if
let messageLabel = self.messageLabel,
let message = messageLabel.text,
message.count > 0 {
flex.addItem(titleLabel).margin(UIEdgeInsets(top: 80, left: 30, bottom: 20, right: 30))
flex.addItem(messageLabel).margin(UIEdgeInsets(top: 0, left: 30, bottom: 30, right: 30))
} else {
flex.addItem(titleLabel).margin(UIEdgeInsets(top: 80, left: 30, bottom: 30, right: 30))
}
if let innerView = self.innerView {
flex.addItem(titleLabel).margin(UIEdgeInsets(top: 80, left: 30, bottom: 20, right: 30))
flex.addItem(innerView)
}
flex.addItem(separatorView).width(100%).height(1).backgroundColor(Theme.current.container.background.lighterColor(percent: 0.3))
if let activityIndicatorView = activityIndicatorView {
flex.addItem(activityIndicatorView).width(50).height(50)
}
flex.addItem(actionsStackView).width(100%).grow(1)
}
super.configureConstraints()
}
func setInnerView(_ view: UIView) {
innerView = view
}
func addMessageLabel() {
guard messageLabel == nil else {
return
}
innerView = UILabel(fontSize: 16)
messageLabel?.textAlignment = .center
messageLabel?.numberOfLines = 0
messageLabel?.textColor = .wildDarkBlue
}
func addActivityIndicatorView() {
guard activityIndicatorView == nil else {
return
}
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white)
}
}
final class ExchangeAlertViewController: BaseViewController<ExchangeAlertView> {
var onDone: (() -> Void)?
override func configureBinds() {
super.configureBinds()
modalPresentationStyle = .overFullScreen
contentView.statusImageView.image = UIImage(named: "info-icon")
contentView.titleLabel.text = title
contentView.titleLabel.flex.markDirty()
contentView.innerView.flex.markDirty()
contentView.flex.markDirty()
contentView.rootFlexContainer.setNeedsLayout()
contentView.rootFlexContainer.flex.layout()
contentView.doneButton.addTarget(self, action: #selector(_onDone), for: .touchUpInside)
contentView.cancelButton.addTarget(self, action: #selector(_onCancel), for: .touchUpInside)
}
func setTradeID(_ id: String) {
contentView.innerView.setTradeID(id)
}
@objc
private func _onDone() {
dismiss(animated: true) {
self.onDone?()
}
}
@objc
private func _onCancel() {
dismiss(animated: true)
}
}
final class ExchangeAlertView: CWBaseAlertView {
let bottomView: UIView
let cancelButton: UIButton
let doneButton: UIButton
let innerView: ExchangeContentAlertView
required init() {
bottomView = UIView()
cancelButton = SecondaryButton(title: NSLocalizedString("cancel", comment: ""))
doneButton = PrimaryButton(title: NSLocalizedString("i_saved_sec_key", comment: ""), fontSize: 14)
innerView = ExchangeContentAlertView()
super.init()
}
override func configureView() {
super.configureView()
isOpaque = false
}
override func configureConstraints() {
contentView.flex.backgroundColor(.white).alignItems(.center).define { flex in
flex.addItem(statusImageView).width(100).height(100).alignSelf(.center).position(.absolute).top(-30)
flex.addItem(titleLabel).margin(UIEdgeInsets(top: 80, left: 30, bottom: 20, right: 30))
flex.addItem(innerView)
}
bottomView.flex.position(.absolute).bottom(10).width(width).height(122).justifyContent(.spaceBetween).define { flex in
flex.addItem(cancelButton).height(56)
flex.addItem(doneButton).height(56)
}
super.configureConstraints()
rootFlexContainer.flex.addItem(bottomView)
}
}
class CWBaseAlertView: BaseFlexView {
private static let approximatedDefaultWidth = 325 as CGFloat
let statusImageView: UIImageView
let contentView: UIView
let titleLabel: UILabel
var width: CGFloat {
return UIScreen.main.bounds.width > CWBaseAlertView.approximatedDefaultWidth
? CWBaseAlertView.approximatedDefaultWidth
: UIScreen.main.bounds.width - 50 // 50 = 2x25 offset
}
required init() {
titleLabel = UILabel(fontSize: 19)
statusImageView = UIImageView(image: nil)
contentView = UIView()
super.init()
}
override func configureView() {
super.configureView()
isOpaque = true
rootFlexContainer.backgroundColor = Theme.current.container.background.withAlphaComponent(0.4)
contentView.layer.masksToBounds = false
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
titleLabel.textColor = UIColor.sumokoinGreen
contentView.layer.shadowRadius = 20
contentView.layer.shadowOffset = CGSize(width: 2, height: 1)
contentView.layer.shadowOpacity = 0.3
contentView.layer.shadowColor = UIColor.sumokoinBlack50.cgColor
// actionsStackView.distribution = .fill
// actionsStackView.alignment = .fill
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.layer.cornerRadius = contentView.frame.size.height * 0.1
}
override func configureConstraints() {
rootFlexContainer.flex.justifyContent(.center).alignItems(.center).define { flex in
flex.addItem(contentView).width(width).minHeight(50)
}
}
}
| 35.867925 | 140 | 0.638085 |
23818de0f1f527cc7eee2ade2bbd906c6a40c48c | 255 | // 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 B<C {
init(c: C) {
{
{
}
{
}
}
{
}
{
}
enum A {
case b
}
let c: A?
if c == .b {
| 11.590909 | 87 | 0.639216 |
79b11ff336931930a23e8db21af7549f09d73201 | 1,107 | //
// StreamingApp.swift
// StreamingApp
//
// Created by Moritz Philip Recke on 21.10.21 for createwithswift.com.
//
import SwiftUI
import AVKit
@main
struct StreamingApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
List {
NavigationLink("Simple video player") {
SimpleVideoPlayerView()
}
NavigationLink("Observing player's status") {
BufferVideoPlayerView()
}
NavigationLink("HLS manifest") {
ManifestVideoPlayerView()
}
NavigationLink(destination: {
UIKitVideoPlayerView()
}, label: {
(Text("PiP ") + Text("UIViewControllerRepresentable").font(.caption))
})
}
.navigationBarTitle("StreamingApp")
}
}
}
}
| 27.675 | 93 | 0.420958 |
79564c99f734aee3454d21d3d907e9678e349f76 | 501 | //
// TableViewCell.swift
// twitter_alamofire_demo
//
// Created by Mayank Gandhi on 8/27/18.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.04 | 65 | 0.672655 |
5df02b964ee29cb065862b2c9687b981ade79f60 | 2,137 | //
// AppDelegate.swift
// Tippy
//
// Created by Carina Boo on 7/10/16.
// Copyright © 2016 Carina Boo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.468085 | 285 | 0.752925 |
4b15c05e060f8073b4cec0e630fad7e93d900e34 | 1,778 | /*
* Copyright (c) 2017 Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
struct QuarterlyGroup: Codable {
let name: String
public var order: Int = 100
init(name: String) {
self.name = name
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
order = try values.decode(Int.self, forKey: .order)
}
}
extension QuarterlyGroup: Hashable {
static func == (lhs: QuarterlyGroup, rhs: QuarterlyGroup) -> Bool {
return lhs.name == rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
| 36.285714 | 80 | 0.711474 |
1dc02daf0a91d72539cc5106164375b4c25e9453 | 958 | //
// DynamicOverlayDragArea.swift
// DynamicOverlay
//
// Created by Gaétan Zanella on 29/01/2022.
// Copyright © 2022 Fabernovel. All rights reserved.
//
import Foundation
import SwiftUI
struct DynamicOverlayDragArea: Equatable {
private let area: ActivatedOverlayArea
init(area: ActivatedOverlayArea) {
self.area = area
}
static var `default`: DynamicOverlayDragArea {
DynamicOverlayDragArea(area: .default)
}
var isEmpty: Bool {
area.isEmpty
}
func contains(_ rect: CGRect) -> Bool {
area.contains(rect)
}
func contains(_ point: CGPoint) -> Bool {
return area.contains(point)
}
}
struct DynamicOverlayDragAreaPreferenceKey: PreferenceKey {
typealias Value = ActivatedOverlayArea
static var defaultValue: ActivatedOverlayArea = .default
static func reduce(value: inout Value, nextValue: () -> Value) {
value.merge(nextValue())
}
}
| 20.382979 | 68 | 0.672234 |
096a4a638ad652a25fde1464d7a9be2ae34fb260 | 2,710 | //
// CenteredCurvedButtonTabBar.swift
// iOS_Bootstrap_Example
//
// Created by Ahmad Mahmoud on 3/10/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
@IBDesignable
class CenteredCurvedButtonTabBar: UITabBar {
private var shapeLayer: CALayer?
private func addShape() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = createPathWithCenteredHalfCircle()
shapeLayer.strokeColor = UIColor.lightGray.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.lineWidth = 1.0
if let oldShapeLayer = self.shapeLayer {
self.layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
}
else {
self.layer.insertSublayer(shapeLayer, at: 0)
}
self.shapeLayer = shapeLayer
}
override func draw(_ rect: CGRect) {
self.addShape()
}
func createPath() -> CGPath {
let height: CGFloat = 37.0
let path = UIBezierPath()
let centerWidth = self.frame.width / 2
path.move(to: CGPoint(x: 0, y: 0)) // start top left
path.addLine(to: CGPoint(x: (centerWidth - height * 2), y: 0)) // the beginning of the trough
// First curve down
path.addCurve(to: CGPoint(x: centerWidth, y: height),
controlPoint1: CGPoint(x: (centerWidth - 30), y: 0),
controlPoint2: CGPoint(x: centerWidth - 35, y: height))
// Second curve up
path.addCurve(to: CGPoint(x: (centerWidth + height * 2), y: 0),
controlPoint1: CGPoint(x: centerWidth + 35, y: height),
controlPoint2: CGPoint(x: (centerWidth + 30), y: 0))
// Complete the rect
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: 0, y: self.frame.height))
path.close()
//
return path.cgPath
}
func createPathWithCenteredHalfCircle() -> CGPath {
let radius: CGFloat = 37.0
let path = UIBezierPath()
let centerWidth = self.frame.width / 2
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: (centerWidth - radius * 2), y: 0))
path.addArc(withCenter: CGPoint(x: centerWidth, y: 0), radius: radius, startAngle: CGFloat(180).degreesToRadians, endAngle: CGFloat(0).degreesToRadians, clockwise: false)
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: 0, y: self.frame.height))
path.close()
return path.cgPath
}
}
| 37.638889 | 178 | 0.611439 |
ffd059d17ee53ef91a03cacd3fcf66c9b46e8778 | 1,291 | //
// TestScriptProfileOriginType.swift
// Asclepius
// Module: R4
//
// Copyright (c) 2022 Bitmatic 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.
/**
This value set defines a set of codes that are used to indicate the profile type of a test system when acting as the
origin within a TestScript.
URL: http://terminology.hl7.org/CodeSystem/testscript-profile-origin-types
ValueSet: http://hl7.org/fhir/ValueSet/testscript-profile-origin-types
*/
public enum TestScriptProfileOriginType: String, AsclepiusPrimitiveType {
/// General FHIR client used to initiate operations against a FHIR server.
case fHIRClient = "FHIR-Client"
/// A FHIR client acting as a Structured Data Capture Form Filler.
case fHIRSDCFormFiller = "FHIR-SDC-FormFiller"
}
| 37.970588 | 117 | 0.745933 |
b90c524c5ed98ed460a8b0a8b88a01ef07651a5a | 1,069 | //
// BlockedAdCategoriesElementHandler.swift
// VastParserSwift
//
// Created by 伊藤大司 on 7/15/20.
// Copyright © 2020 DJ110. All rights reserved.
//
import Foundation
class BlockedAdCategoriesElementHandler: ElementHandler {
let rank: Int = 3
func execute(state: ParseState, elementName: String, attributes attributeDict: [String : String]) {
guard let authority : String = attributeDict["authority"] else {
state.errors.append(ParseError(message: "BlockedAdCategories should have authority attr"))
return
}
var blockedAdCategories = BlockedAdCategories()
blockedAdCategories.authority = authority
if state.isWrapper() {
state.vast.vastAd?.wrapper?.blockedAdCategories.append(blockedAdCategories)
state.updateParseElement(rank: rank, elementName: elementName)
} else {
state.errors.append(ParseError(message: "BlockedAdCategories should be under Wrapper element"))
}
}
}
| 30.542857 | 107 | 0.648269 |
5d575aa12d2f65ae29e3318f504bdad3a3277056 | 1,577 | import SwiftUI
var AnArrays : [String] = [ "eins", "zwei", "drei", "vier", "fünf"]
struct PickerTest: View {
@State var Gepickt : String = ""
var body : some View {
NavigationView{
VStack {
NavigationLink(destination: AuswahlPick(gewählt: $Gepickt)) {
HStack {
Text("PickerMaSelf")
.foregroundColor(Color.black)
Spacer()
Text(Gepickt.count > 0 ? Gepickt : "Pick One ?") .foregroundColor(Color.gray)
Image("chevron.right") .foregroundColor(Color.gray)
.padding(.trailing)
}
}
}
}
}
}
struct AuswahlPick: View {
@Binding var gewählt : String
@Environment(\.presentationMode) var presentationMode
var body: some View {
Form{
ForEach(AnArrays, id: \.self){ x in
Button(action: {
self.gewählt = "\(x)"
self.presentationMode.wrappedValue.dismiss()
}) {
Text("\(x)")
.foregroundColor(Color.black)
}
}
}
}
}
struct PickerTest_Previews: PreviewProvider {
static var previews: some View {
PickerTest()
}
}
| 31.54 | 112 | 0.406468 |
e67c78602b228765f0903b856e07d48c298b60bc | 4,929 | //
// CarsListViewController.swift
// CarLens
//
import UIKit
final class CarsListViewController: TypedViewController<CarsListView>,
UICollectionViewDataSource, UICollectionViewDelegate {
private var didCheckCarScroll = false
private let carsDataService: CarsDataService
private let discoveredCar: Car?
private var cars = [Car]()
/// Enum describing events that can be triggered by this controller
///
/// - didTapDismiss: send when user want to dismiss the view
/// - didTapBackButton: send when user taps on the back arrow on screen
enum Event {
case didTapDismiss
case didTapBackButton
}
/// Callback with triggered event
var eventTriggered: ((Event) -> Void)?
/// Initializes the view controller with given parameters
///
/// - Parameters:
/// - discoveredCar: Car to be displayed by the view controller
/// - carsDataService: Data service for retrieving informations about cars
init(discoveredCar: Car? = nil, carsDataService: CarsDataService) {
self.discoveredCar = discoveredCar
self.carsDataService = carsDataService
super.init(viewMaker: CarsListView(discoveredCar: discoveredCar,
availableCars: carsDataService.getNumberOfCars()))
}
/// SeeAlso: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityIdentifier = "carsList/view/main"
cars = carsDataService.getAvailableCars()
customView.collectionView.dataSource = self
customView.collectionView.delegate = self
customView.collectionView.register(cell: CarListCollectionViewCell.self)
customView.recognizeButton.addTarget(self, action: #selector(recognizeButtonTapAction), for: .touchUpInside)
customView.topView.backButton.addTarget(self, action: #selector(backButtonTapAction), for: .touchUpInside)
}
/// SeeAlso: UIViewController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
invalidateDiscoveredProgressView()
}
/// SeeAlso: UIViewController
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animateVisibleCells()
customView.topView.progressView.invalidateChart(animated: true)
}
/// SeeAlso: UIViewController
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard !didCheckCarScroll else { return }
scrollToDiscoveredCarIfNeeded()
didCheckCarScroll = true
}
@objc private func recognizeButtonTapAction() {
eventTriggered?(discoveredCar == nil ? .didTapBackButton : .didTapDismiss)
}
@objc private func backButtonTapAction() {
eventTriggered?(.didTapBackButton)
}
private func scrollToDiscoveredCarIfNeeded() {
guard let discoveredCar = discoveredCar, let index = cars.index(of: discoveredCar) else { return }
let indexPath = IndexPath(item: index, section: 0)
customView.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}
private func animateVisibleCells() {
let cells = customView.collectionView.visibleCells.compactMap { $0 as? CarListCollectionViewCell }
cells.forEach {
if $0.isCurrentlyPrimary {
$0.invalidateCharts(animated: true)
} else {
$0.clearCharts(animated: false)
}
}
}
private func invalidateDiscoveredProgressView() {
let discoveredCars = carsDataService.getNumberOfDiscoveredCars()
let availableCars = carsDataService.getNumberOfCars()
customView.topView.progressView.setup(currentNumber: discoveredCars,
maximumNumber: availableCars,
invalidateChartInstantly: false)
}
/// SeeAlso: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return carsDataService.getNumberOfCars()
}
/// SeeAlso: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell: CarListCollectionViewCell = collectionView.dequeueReusableCell(for: indexPath) else {
return UICollectionViewCell()
}
cell.setup(with: cars[indexPath.row])
return cell
}
/// SeeAlso: UICollectionViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
animateVisibleCells()
}
/// SeeAlso: UICollectionViewDelegate
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
animateVisibleCells()
}
}
| 36.511111 | 116 | 0.675188 |
188a12b68828fa1d5f4faa8342d68dcda404e311 | 5,502 | //
// ARSession+Rx.swift
// Rx+ARKitSamples
//
// Created by 윤중현 on 2018. 10. 4..
// Copyright © 2018년 tokijh. All rights reserved.
//
import ARKit
import RxSwift
import RxCocoa
extension Reactive where Base: ARSession {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<ARSession, ARSessionDelegate> {
return RxARSessionDelegateProxy.proxy(for: base)
}
// MARK ARSessionDelegate
// Reactive wrapper for delegate method `session(_:didUpdate:)`
public var didUpdateFrame: ControlEvent<ARFrame> {
let source: Observable<ARFrame> = delegate
.methodInvoked(#selector(ARSessionDelegate.session(_:didUpdate:) as ((ARSessionDelegate) -> (ARSession, ARFrame) -> Void)?))
.map { value -> ARFrame in
let camera = try castOrThrow(ARFrame.self, value[1])
return camera
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:didAdd:)`
public var didAddAnchors: ControlEvent<[ARAnchor]> {
let source = delegate.methodInvoked(#selector(ARSessionDelegate.session(_:didAdd:)))
.map { value -> [ARAnchor] in
let anchors = try castOrThrow([ARAnchor].self, value[1])
return anchors
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:didAdd:)`
public var didUpdateAnchors: ControlEvent<[ARAnchor]> {
let source = delegate
.methodInvoked(#selector(ARSessionDelegate.session(_:didUpdate:) as ((ARSessionDelegate) -> (ARSession, [ARAnchor]) -> Void)?))
.map { value -> [ARAnchor] in
let anchors = try castOrThrow([ARAnchor].self, value[1])
return anchors
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:didRemove:)`
public var didRemoveAnchors: ControlEvent<[ARAnchor]> {
let source = delegate.methodInvoked(#selector(ARSessionDelegate.session(_:didRemove:)))
.map { value -> [ARAnchor] in
let anchors = try castOrThrow([ARAnchor].self, value[1])
return anchors
}
return ControlEvent(events: source)
}
// MARK ARSessionObserver
/// Reactive wrapper for delegate method `session(_:didFailWithError:)`
public var sessionDidFailWithError: ControlEvent<Error> {
let source = delegate.methodInvoked(#selector(ARSessionObserver.session(_:didFailWithError:)))
.map { value -> Error in
let error = try castOrThrow(Error.self, value[1])
return error
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:cameraDidChangeTrackingState:)`
public var sessionCameraDidChangeTrackingState: ControlEvent<ARCamera> {
let source = delegate.methodInvoked(#selector(ARSessionObserver.session(_:cameraDidChangeTrackingState:)))
.map { value -> ARCamera in
let camera = try castOrThrow(ARCamera.self, value[1])
return camera
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:sessionWasInterrupted:)`
public var sessionWasInterrupted: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(ARSessionObserver.sessionWasInterrupted(_:)))
.map({ _ in })
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:sessionInterruptionEnded:)`
public var sessionInterruptionEnded: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(ARSessionObserver.sessionInterruptionEnded(_:)))
.map({ _ in })
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `session(_:sessionInterruptionEnded:)`
public var sessionDidOutputAudioSampleBuffer: ControlEvent<CMSampleBuffer> {
let source = delegate.methodInvoked(#selector(ARSessionObserver.session(_:didOutputAudioSampleBuffer:)))
.map { value -> CMSampleBuffer in
let sampleBuffer = try castOrThrow(CMSampleBuffer.self, value[1])
return sampleBuffer
}
return ControlEvent(events: source)
}
public var run: Binder<(ARConfiguration, ARSession.RunOptions)> {
return Binder<(ARConfiguration, ARSession.RunOptions)>(base) { (base, value) in
let (configuration, options) = value
base.run(configuration, options: options)
}
}
public var pause: Binder<Void> {
return Binder<Void>(base) { (base, value) in
base.pause()
}
}
/// Installs delegate as forwarding delegate on `delegate`.
/// Delegate won't be retained.
///
/// It enables using normal delegate mechanism with reactive delegate mechanism.
///
/// - parameter delegate: Delegate object.
/// - returns: Disposable object that can be used to unbind the delegate.
public func setDelegate(_ delegate: ARSessionDelegate) -> Disposable {
return RxARSessionDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
}
}
| 40.160584 | 139 | 0.647219 |
e508df39b747ab332edfbf7ed4b98dc0cf13b293 | 4,947 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
#if compiler(>=5.5) && canImport(_Concurrency)
import SotoCore
// MARK: Paginators
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension MigrationHubStrategy {
/// Retrieves detailed information about a specified server.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func getServerDetailsPaginator(
_ input: GetServerDetailsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<GetServerDetailsRequest, GetServerDetailsResponse> {
return .init(
input: input,
command: getServerDetails,
inputKey: \GetServerDetailsRequest.nextToken,
outputKey: \GetServerDetailsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Retrieves a list of all the application components (processes).
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func listApplicationComponentsPaginator(
_ input: ListApplicationComponentsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<ListApplicationComponentsRequest, ListApplicationComponentsResponse> {
return .init(
input: input,
command: listApplicationComponents,
inputKey: \ListApplicationComponentsRequest.nextToken,
outputKey: \ListApplicationComponentsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Retrieves a list of all the installed collectors.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func listCollectorsPaginator(
_ input: ListCollectorsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<ListCollectorsRequest, ListCollectorsResponse> {
return .init(
input: input,
command: listCollectors,
inputKey: \ListCollectorsRequest.nextToken,
outputKey: \ListCollectorsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Retrieves a list of all the imports performed.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func listImportFileTaskPaginator(
_ input: ListImportFileTaskRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<ListImportFileTaskRequest, ListImportFileTaskResponse> {
return .init(
input: input,
command: listImportFileTask,
inputKey: \ListImportFileTaskRequest.nextToken,
outputKey: \ListImportFileTaskResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Returns a list of all the servers.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func listServersPaginator(
_ input: ListServersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<ListServersRequest, ListServersResponse> {
return .init(
input: input,
command: listServers,
inputKey: \ListServersRequest.nextToken,
outputKey: \ListServersResponse.nextToken,
logger: logger,
on: eventLoop
)
}
}
#endif // compiler(>=5.5) && canImport(_Concurrency)
| 35.847826 | 107 | 0.621993 |
794b7ec74cc843a962c3f6ec00c10eee7f9b9f4f | 2,310 | //
// Persistence.swift
// StuddyBud
//
// Created by user175571 on 3/27/21.
//
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
}
do {
try viewContext.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)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "StuddyBud")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
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)")
}
})
}
}
| 41.25 | 199 | 0.630736 |
388ca255bb4e3c409db6ca6fa24127356ad63146 | 3,237 | //
// Business.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class Business: NSObject {
let name: String?
let address: String?
let imageURL: URL?
let categories: String?
let distance: String?
let ratingImageURL: URL?
let reviewCount: NSNumber?
init(dictionary: NSDictionary) {
name = dictionary["name"] as? String
let imageURLString = dictionary["image_url"] as? String
if imageURLString != nil {
imageURL = URL(string: imageURLString!)!
} else {
imageURL = nil
}
let location = dictionary["location"] as? NSDictionary
var address = ""
if location != nil {
let addressArray = location!["address"] as? NSArray
if addressArray != nil && addressArray!.count > 0 {
address = addressArray![0] as! String
}
let neighborhoods = location!["neighborhoods"] as? NSArray
if neighborhoods != nil && neighborhoods!.count > 0 {
if !address.isEmpty {
address += ", "
}
address += neighborhoods![0] as! String
}
}
self.address = address
let categoriesArray = dictionary["categories"] as? [[String]]
if categoriesArray != nil {
var categoryNames = [String]()
for category in categoriesArray! {
let categoryName = category[0]
categoryNames.append(categoryName)
}
categories = categoryNames.joined(separator: ", ")
} else {
categories = nil
}
let distanceMeters = dictionary["distance"] as? NSNumber
if distanceMeters != nil {
let milesPerMeter = 0.000621371
distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue)
} else {
distance = nil
}
let ratingImageURLString = dictionary["rating_img_url_large"] as? String
if ratingImageURLString != nil {
ratingImageURL = URL(string: ratingImageURLString!)
} else {
ratingImageURL = nil
}
reviewCount = dictionary["review_count"] as? NSNumber
}
class func businesses(array: [NSDictionary]) -> [Business] {
var businesses = [Business]()
for dictionary in array {
let business = Business(dictionary: dictionary)
businesses.append(business)
}
return businesses
}
class func searchWithTerm(term: String, completion: @escaping ([Business]?, Error?) -> Void) {
_ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion)
}
class func searchWithTerm(term: String, sort: YelpSortMode?, distance: YelpDistance?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void {
_ = YelpClient.sharedInstance.searchWithTerm(term, sort: sort, distance:distance, categories: categories, deals: deals, completion: completion)
}
}
| 34.073684 | 189 | 0.571517 |
db249b8dad4b3a04e73a9dfbdaddaab69d3900d6 | 604 | //
// CardDetails.swift
// SbankenClient
//
// Created by Øyvind Tjervaag on 19/03/2018.
// Copyright © 2018 SBanken. All rights reserved.
//
import Foundation
public class CardDetails: Codable {
public let cardNumber: String?
public let currencyAmount: Double?
public let currencyRate: Double?
public let merchantCategoryCode: String?
public let merchantCategoryDescription: String?
public let merchantCity: String?
public let merchantName: String?
public let originalCurrencyCode: String?
public let purchaseDate: Date?
public let transactionId: String?
}
| 26.26087 | 51 | 0.735099 |
c1fd79ee468730dfc0873789303cb73734433e95 | 1,654 | //
// FormUtils.swift
// UnitTests
//
// Created by Vlad Z. on 6/4/20.
// Copyright © 2020 Octo Ent. All rights reserved.
//
import UIKit
import Foundation
public enum FormInputState {
case active
case inactive
}
public enum FormValidationState {
case valid
case invalid
case inactive
}
public struct FormInputKeyboardConfig {
public var isSecure: Bool = false
public var textContentType: UITextContentType?
public var keyboardType: UIKeyboardType = .default
public var returnKeyType: UIReturnKeyType = .default
public var autocapitalizationType: UITextAutocapitalizationType = .none
public init(textContentType: UITextContentType? = nil,
keyboardType: UIKeyboardType = .default,
returnKeyType: UIReturnKeyType = .default,
isSecure: Bool = false,
autocapitalizationType: UITextAutocapitalizationType = .none) {
self.textContentType = textContentType
self.keyboardType = keyboardType
self.returnKeyType = returnKeyType
self.isSecure = isSecure
self.autocapitalizationType = autocapitalizationType
}
}
public struct FormInputConfiguration {
public var inputFont: UIFont
public var placeholderFont: UIFont
public var titleColor: UIColor
public var inputColor: UIColor
public var invalidColor: UIColor
public var placeholderColor: UIColor
public init() {
inputFont = UIFont()
placeholderFont = UIFont()
titleColor = .black
inputColor = .black
invalidColor = .red
placeholderColor = .gray
}
}
| 26.253968 | 79 | 0.677146 |
ab8ac875b14f709e78f8c572839c107bf3e34caf | 981 | // Telegram-vapor-bot - Telegram Bot Swift SDK.
// This file is autogenerated by API/generate_wrappers.rb script.
/**
Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.
SeeAlso Telegram Bot API Reference:
[BotCommandScopeChatAdministrators](https://core.telegram.org/bots/api#botcommandscopechatadministrators)
*/
public final class TGBotCommandScopeChatAdministrators: Codable {
/// Custom keys for coding/decoding `BotCommandScopeChatAdministrators` struct
public enum CodingKeys: String, CodingKey {
case type = "type"
case chatId = "chat_id"
}
/// Scope type, must be chat_administrators
public var type: String
/// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
public var chatId: TGChatId
public init (type: String, chatId: TGChatId) {
self.type = type
self.chatId = chatId
}
}
| 33.827586 | 118 | 0.730887 |
8a1fab5c4f4c86c851f4a4020c91a59ed2521f60 | 861 | //
// SCProfileStatisticsController.swift
// DiabloAssistant
//
// Created by Stephen Cao on 2/6/19.
// Copyright © 2019 Stephen Cao. All rights reserved.
//
import UIKit
class SCProfileStatisticsController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var basicInfoLabel: UILabel!
var viewModel: SCProfileViewModel?{
didSet{
guard let text = viewModel?.heroStatsDescription else{
return
}
textView.text = text
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.scrollRangeToVisible(NSMakeRange(0, 0))
}
func setBasicInfoContent(content: String){
basicInfoLabel.text = content
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 23.27027 | 66 | 0.641115 |
f78ba8176cc2c24991a159c43396436d1d5f2dc1 | 22,169 | //
// FishHookProtection.swift
// FishHookProtect
//
// Created by jintao on 2019/3/25.
// Copyright © 2019 jintao. All rights reserved.
//
import Foundation
import MachO
#if arch(arm64)
@inline(__always)
private func readUleb128(ptr: inout UnsafeMutablePointer<UInt8>, end: UnsafeMutablePointer<UInt8>) -> UInt64 {
var result: UInt64 = 0
var bit = 0
var readNext = true
repeat {
if ptr == end {
assert(false, "malformed uleb128")
}
let slice = UInt64(ptr.pointee & 0x7f)
if bit > 63 {
assert(false, "uleb128 too big for uint64")
} else {
result |= (slice << bit)
bit += 7
}
readNext = ((ptr.pointee & 0x80) >> 7) == 1
ptr += 1
} while (readNext)
return result
}
@inline(__always)
private func readSleb128(ptr: inout UnsafeMutablePointer<UInt8>, end: UnsafeMutablePointer<UInt8>) -> Int64 {
var result: Int64 = 0
var bit: Int = 0
var byte: UInt8
repeat {
if (ptr == end) {
assert(false, "malformed sleb128")
}
byte = ptr.pointee
result |= (((Int64)(byte & 0x7f)) << bit)
bit += 7
ptr += 1
} while (byte & 0x80) == 1
// sign extend negative numbers
if ( (byte & 0x40) != 0 ) {
result |= -1 << bit
}
return result
}
public class FishHookChecker {
@inline(__always)
static public func denyFishHook(_ symbol: String) {
var symbolAddress: UnsafeMutableRawPointer?
for imgIndex in 0..<_dyld_image_count() {
if let image = _dyld_get_image_header(imgIndex) {
if symbolAddress == nil {
_ = SymbolFound.lookSymbol(symbol, at: image, imageSlide: _dyld_get_image_vmaddr_slide(imgIndex), symbolAddress: &symbolAddress)
}
if let symbolPointer = symbolAddress {
var oldMethod: UnsafeMutableRawPointer?
FishHook.replaceSymbol(symbol, at: image, imageSlide: _dyld_get_image_vmaddr_slide(imgIndex), newMethod: symbolPointer, oldMethod: &oldMethod)
}
}
}
}
@inline(__always)
static public func denyFishHook(_ symbol: String, at image: UnsafePointer<mach_header>, imageSlide slide: Int) {
var symbolAddress: UnsafeMutableRawPointer?
if SymbolFound.lookSymbol(symbol, at: image, imageSlide: slide, symbolAddress: &symbolAddress), let symbolPointer = symbolAddress {
var oldMethod: UnsafeMutableRawPointer?
FishHook.replaceSymbol(symbol, at: image, imageSlide: slide, newMethod: symbolPointer, oldMethod: &oldMethod)
}
}
}
// MARK: - SymbolFound
internal class SymbolFound {
static private let BindTypeThreadedRebase = 102
@inline(__always)
static func lookSymbol(_ symbol: String, at image: UnsafePointer<mach_header>, imageSlide slide: Int, symbolAddress: inout UnsafeMutableRawPointer?) -> Bool {
// target cmd
var linkeditCmd: UnsafeMutablePointer<segment_command_64>!
var dyldInfoCmd: UnsafeMutablePointer<dyld_info_command>!
var allLoadDylds = [String]()
guard var curCmdPointer = UnsafeMutableRawPointer(bitPattern: UInt(bitPattern: image)+UInt(MemoryLayout<mach_header_64>.size)) else {
return false
}
// all cmd
for _ in 0..<image.pointee.ncmds {
let curCmd = curCmdPointer.assumingMemoryBound(to: segment_command_64.self)
switch UInt32(curCmd.pointee.cmd) {
case UInt32(LC_SEGMENT_64):
let offset = MemoryLayout.size(ofValue: curCmd.pointee.cmd) + MemoryLayout.size(ofValue: curCmd.pointee.cmdsize)
let curCmdName = String(cString: curCmdPointer.advanced(by: offset).assumingMemoryBound(to: Int8.self))
if (curCmdName == SEG_LINKEDIT) {
linkeditCmd = curCmd
}
case LC_DYLD_INFO_ONLY, UInt32(LC_DYLD_INFO):
dyldInfoCmd = curCmdPointer.assumingMemoryBound(to: dyld_info_command.self)
case UInt32(LC_LOAD_DYLIB), LC_LOAD_WEAK_DYLIB, LC_LOAD_UPWARD_DYLIB, LC_REEXPORT_DYLIB:
let loadDyldCmd = curCmdPointer.assumingMemoryBound(to: dylib_command.self)
let loadDyldNameOffset = Int(loadDyldCmd.pointee.dylib.name.offset)
let loadDyldNamePointer = curCmdPointer.advanced(by: loadDyldNameOffset).assumingMemoryBound(to: Int8.self)
let loadDyldName = String(cString: loadDyldNamePointer)
allLoadDylds.append(loadDyldName)
default:
break
}
curCmdPointer += Int(curCmd.pointee.cmdsize)
}
if linkeditCmd == nil || dyldInfoCmd == nil { return false }
let linkeditBase = UInt64(slide + Int(linkeditCmd.pointee.vmaddr) - Int(linkeditCmd.pointee.fileoff))
// look by LazyBindInfo
let lazyBindSize = Int(dyldInfoCmd.pointee.lazy_bind_size)
if (lazyBindSize > 0) {
if let lazyBindInfoCmd = UnsafeMutablePointer<UInt8>(bitPattern: UInt(linkeditBase + UInt64(dyldInfoCmd.pointee.lazy_bind_off))),
lookLazyBindSymbol(symbol, symbolAddr: &symbolAddress, lazyBindInfoCmd: lazyBindInfoCmd, lazyBindInfoSize: lazyBindSize, allLoadDylds: allLoadDylds) {
return true
}
}
// look by NonLazyBindInfo
let bindSize = Int(dyldInfoCmd.pointee.bind_size)
if (bindSize > 0) {
if let bindCmd = UnsafeMutablePointer<UInt8>(bitPattern: UInt(linkeditBase + UInt64(dyldInfoCmd.pointee.bind_off))),
lookBindSymbol(symbol, symbolAddr: &symbolAddress, bindInfoCmd: bindCmd, bindInfoSize: bindSize, allLoadDylds: allLoadDylds) {
return true
}
}
return false
}
// LazySymbolBindInfo
@inline(__always)
private static func lookLazyBindSymbol(_ symbol: String, symbolAddr: inout UnsafeMutableRawPointer?, lazyBindInfoCmd: UnsafeMutablePointer<UInt8>, lazyBindInfoSize: Int, allLoadDylds: [String]) -> Bool {
var ptr = lazyBindInfoCmd
let lazyBindingInfoEnd = lazyBindInfoCmd.advanced(by: Int(lazyBindInfoSize))
var ordinal: Int = -1
var foundSymbol = false
var addend = 0
var type: Int32 = 0
Label: while ptr < lazyBindingInfoEnd {
let immediate = Int32(ptr.pointee) & BIND_IMMEDIATE_MASK
let opcode = Int32(ptr.pointee) & BIND_OPCODE_MASK
ptr += 1
switch opcode {
case BIND_OPCODE_DONE:
continue
// ORDINAL DYLIB
case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
ordinal = Int(immediate)
case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
ordinal = Int(readUleb128(ptr: &ptr, end: lazyBindingInfoEnd))
case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
if immediate == 0 {
ordinal = 0
} else {
ordinal = Int(BIND_OPCODE_MASK | immediate)
}
// symbol
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
let symbolName = String(cString: ptr + 1)
if (symbolName == symbol) {
foundSymbol = true
}
while ptr.pointee != 0 {
ptr += 1
}
ptr += 1 // '00'
case BIND_OPCODE_SET_TYPE_IMM:
type = immediate
continue
// sleb
case BIND_OPCODE_SET_ADDEND_SLEB:
addend = Int(readSleb128(ptr: &ptr, end: lazyBindingInfoEnd))
// uleb
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, BIND_OPCODE_ADD_ADDR_ULEB:
_ = readUleb128(ptr: &ptr, end: lazyBindingInfoEnd)
// bind action
case BIND_OPCODE_DO_BIND:
if (foundSymbol) {
break Label
} else {
continue
}
default:
assert(false, "bad lazy bind opcode")
return false
}
}
assert(ordinal <= allLoadDylds.count)
if (foundSymbol && ordinal >= 0 && allLoadDylds.count > 0), ordinal <= allLoadDylds.count, type != BindTypeThreadedRebase {
let imageName = allLoadDylds[ordinal-1]
var tmpSymbolAddress: UnsafeMutableRawPointer?
if lookExportedSymbol(symbol, exportImageName: imageName, symbolAddress: &tmpSymbolAddress), let symbolPointer = tmpSymbolAddress {
symbolAddr = symbolPointer + addend
return true
}
}
return false
}
// NonLazySymbolBindInfo
@inline(__always)
private static func lookBindSymbol(_ symbol: String, symbolAddr: inout UnsafeMutableRawPointer?, bindInfoCmd: UnsafeMutablePointer<UInt8>, bindInfoSize: Int, allLoadDylds: [String]) -> Bool {
var ptr = bindInfoCmd
let bindingInfoEnd = bindInfoCmd.advanced(by: Int(bindInfoSize))
var ordinal: Int = -1
var foundSymbol = false
var addend = 0
var type: Int32 = 0
Label: while ptr < bindingInfoEnd {
let immediate = Int32(ptr.pointee) & BIND_IMMEDIATE_MASK
let opcode = Int32(ptr.pointee) & BIND_OPCODE_MASK
ptr += 1
switch opcode {
case BIND_OPCODE_DONE:
break Label
// ORDINAL DYLIB
case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
ordinal = Int(immediate)
case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
ordinal = Int(readUleb128(ptr: &ptr, end: bindingInfoEnd))
case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
if immediate == 0 {
ordinal = 0
} else {
ordinal = Int(Int8(BIND_OPCODE_MASK | immediate))
}
// symbol
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
let symbolName = String(cString: ptr + 1)
if (symbolName == symbol) {
foundSymbol = true
}
while ptr.pointee != 0 {
ptr += 1
}
ptr += 1 // '00'
case BIND_OPCODE_SET_TYPE_IMM:
type = immediate
continue
// sleb
case BIND_OPCODE_SET_ADDEND_SLEB:
addend = Int(readSleb128(ptr: &ptr, end: bindingInfoEnd))
// uleb
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, BIND_OPCODE_ADD_ADDR_ULEB:
_ = readUleb128(ptr: &ptr, end: bindingInfoEnd)
// do bind action
case BIND_OPCODE_DO_BIND, BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
if (foundSymbol) {
break Label
}
case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
if (foundSymbol) {
break Label
} else {
_ = readUleb128(ptr: &ptr, end: bindingInfoEnd)
}
case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
if (foundSymbol) {
break Label
} else {
_ = readUleb128(ptr: &ptr, end: bindingInfoEnd) // count
_ = readUleb128(ptr: &ptr, end: bindingInfoEnd) // skip
}
case BIND_OPCODE_THREADED:
switch immediate {
case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB:
_ = readUleb128(ptr: &ptr, end: bindingInfoEnd)
case BIND_SUBOPCODE_THREADED_APPLY:
if (foundSymbol) {
// ImageLoaderMachO::bindLocation case BIND_TYPE_THREADED_REBASE
assert(false, "maybe bind_type is BIND_TYPE_THREADED_REBASE, don't handle")
return false
}
continue Label
default:
assert(false, "bad bind subopcode")
return false
}
default:
assert(false, "bad bind opcode")
return false
}
}
assert(ordinal <= allLoadDylds.count)
if (foundSymbol && ordinal >= 0 && allLoadDylds.count > 0), ordinal <= allLoadDylds.count, type != BindTypeThreadedRebase {
let imageName = allLoadDylds[ordinal-1]
var tmpSymbolAddress: UnsafeMutableRawPointer?
if lookExportedSymbol(symbol, exportImageName: imageName, symbolAddress: &tmpSymbolAddress), let symbolPointer = tmpSymbolAddress {
symbolAddr = symbolPointer + addend
return true
}
}
return false
}
// ExportSymbol
@inline(__always)
private static func lookExportedSymbol(_ symbol: String, exportImageName: String, symbolAddress: inout UnsafeMutableRawPointer?) -> Bool {
var rpathImage: String?
// @rpath
if (exportImageName.contains("@rpath")) {
rpathImage = exportImageName.components(separatedBy: "/").last
}
for index in 0..<_dyld_image_count() {
// imageName
let currentImageName = String(cString: _dyld_get_image_name(index))
if let tmpRpathImage = rpathImage {
if (!currentImageName.contains(tmpRpathImage)) {
continue
}
} else if (String(cString: _dyld_get_image_name(index)) != exportImageName) {
continue
}
if let pointer = _lookExportedSymbol(symbol, image: _dyld_get_image_header(index), imageSlide: _dyld_get_image_vmaddr_slide(index)) {
// found
symbolAddress = UnsafeMutableRawPointer(mutating: pointer)
return true
} else {
// not found, look at ReExport dylibs
var allReExportDylibs = [String]()
if let currentImage = _dyld_get_image_header(index),
var curCmdPointer = UnsafeMutableRawPointer(bitPattern: UInt(bitPattern: currentImage)+UInt(MemoryLayout<mach_header_64>.size)) {
for _ in 0..<currentImage.pointee.ncmds {
let curCmd = curCmdPointer.assumingMemoryBound(to: segment_command_64.self)
if (curCmd.pointee.cmd == LC_REEXPORT_DYLIB) {
let reExportDyldCmd = curCmdPointer.assumingMemoryBound(to: dylib_command.self)
let nameOffset = Int(reExportDyldCmd.pointee.dylib.name.offset)
let namePointer = curCmdPointer.advanced(by: nameOffset).assumingMemoryBound(to: Int8.self)
let reExportDyldName = String(cString: namePointer)
allReExportDylibs.append(reExportDyldName)
}
curCmdPointer += Int(curCmd.pointee.cmdsize)
}
}
for reExportDyld in allReExportDylibs {
if lookExportedSymbol(symbol, exportImageName: reExportDyld, symbolAddress: &symbolAddress) {
return true
}
}
// not found, stop
return false
}
}
return false
}
// look export symbol by export trie
@inline(__always)
static private func _lookExportedSymbol(_ symbol: String, image: UnsafePointer<mach_header>, imageSlide slide: Int) -> UnsafeMutableRawPointer? {
// target cmd
var linkeditCmd: UnsafeMutablePointer<segment_command_64>!
var dyldInfoCmd: UnsafeMutablePointer<dyld_info_command>!
var exportCmd: UnsafeMutablePointer<linkedit_data_command>!
guard var curCmdPointer = UnsafeMutableRawPointer(bitPattern: UInt(bitPattern: image)+UInt(MemoryLayout<mach_header_64>.size)) else {
return nil
}
// cmd
for _ in 0..<image.pointee.ncmds {
let curCmd = curCmdPointer.assumingMemoryBound(to: segment_command_64.self)
switch UInt32(curCmd.pointee.cmd) {
case UInt32(LC_SEGMENT_64):
let offset = MemoryLayout.size(ofValue: curCmd.pointee.cmd) + MemoryLayout.size(ofValue: curCmd.pointee.cmdsize)
let curCmdName = String(cString: curCmdPointer.advanced(by: offset).assumingMemoryBound(to: Int8.self))
if (curCmdName == SEG_LINKEDIT) {
linkeditCmd = curCmd
}
case LC_DYLD_INFO_ONLY, UInt32(LC_DYLD_INFO):
dyldInfoCmd = curCmdPointer.assumingMemoryBound(to: dyld_info_command.self)
case LC_DYLD_EXPORTS_TRIE:
exportCmd = curCmdPointer.assumingMemoryBound(to: linkedit_data_command.self)
default:
break
}
curCmdPointer += Int(curCmd.pointee.cmdsize)
}
// export trie info
let hasDyldInfo = dyldInfoCmd != nil && dyldInfoCmd.pointee.export_size != 0
let hasExportTrie = exportCmd != nil && exportCmd.pointee.datasize != 0
if linkeditCmd == nil || (!hasDyldInfo && !hasExportTrie) {
return nil
}
let linkeditBase = Int(slide + Int(linkeditCmd.pointee.vmaddr) - Int(linkeditCmd.pointee.fileoff))
let exportOff = hasExportTrie ? exportCmd.pointee.dataoff : dyldInfoCmd.pointee.export_off
let exportSize = hasExportTrie ? exportCmd.pointee.datasize : dyldInfoCmd.pointee.export_size
guard let exportedInfo = UnsafeMutableRawPointer(bitPattern: linkeditBase + Int(exportOff))?.assumingMemoryBound(to: UInt8.self) else { return nil }
let start = exportedInfo
let end = exportedInfo + Int(exportSize)
// export symbol location
if var symbolLocation = lookExportedSymbolByTrieWalk(targetSymbol: symbol, start: start, end: end, currentLocation: start, currentSymbol: "") {
let flags = readUleb128(ptr: &symbolLocation, end: end)
let returnSymbolAddress = { () -> UnsafeMutableRawPointer in
let machO = image.withMemoryRebound(to: Int8.self, capacity: 1, { $0 })
let symbolAddress = machO.advanced(by: Int(readUleb128(ptr: &symbolLocation, end: end)))
return UnsafeMutableRawPointer(mutating: symbolAddress)
}
switch flags & UInt64(EXPORT_SYMBOL_FLAGS_KIND_MASK) {
case UInt64(EXPORT_SYMBOL_FLAGS_KIND_REGULAR):
// runResolver is false by bind or lazyBind
return returnSymbolAddress()
case UInt64(EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL):
if (flags & UInt64(EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) != 0) {
return nil
}
return returnSymbolAddress()
case UInt64(EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE):
if (flags & UInt64(EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) != 0) {
return nil
}
return UnsafeMutableRawPointer(bitPattern: UInt(readUleb128(ptr: &symbolLocation, end: end)))
default:
break
}
}
return nil
}
// ExportSymbol
@inline(__always)
static private func lookExportedSymbolByTrieWalk(targetSymbol: String, start: UnsafeMutablePointer<UInt8>, end: UnsafeMutablePointer<UInt8>, currentLocation location: UnsafeMutablePointer<UInt8>, currentSymbol: String) -> UnsafeMutablePointer<UInt8>? {
var ptr = location
while ptr <= end {
// terminalSize
var terminalSize = UInt64(ptr.pointee)
ptr += 1
if terminalSize > 127 {
ptr -= 1
terminalSize = readUleb128(ptr: &ptr, end: end)
}
if terminalSize != 0 {
return currentSymbol == targetSymbol ? ptr : nil
}
// children
let children = ptr.advanced(by: Int(terminalSize))
if children >= end {
// end
return nil
}
let childrenCount = children.pointee
ptr = children + 1
// nodes
for _ in 0..<childrenCount {
let nodeLabel = ptr.withMemoryRebound(to: CChar.self, capacity: 1, { $0 })
// node offset
while ptr.pointee != 0 {
ptr += 1
}
ptr += 1 // = "00"
let nodeOffset = Int(readUleb128(ptr: &ptr, end: end))
// node
if let nodeSymbol = String(cString: nodeLabel, encoding: .utf8) {
let tmpCurrentSymbol = currentSymbol + nodeSymbol
if !targetSymbol.contains(tmpCurrentSymbol) {
continue
}
if nodeOffset != 0 && (start + nodeOffset <= end) {
let location = start.advanced(by: nodeOffset)
if let symbolLocation = lookExportedSymbolByTrieWalk(targetSymbol: targetSymbol, start: start, end: end, currentLocation: location, currentSymbol: tmpCurrentSymbol) {
return symbolLocation
}
}
}
}
}
return nil
}
}
#endif
| 42.550864 | 256 | 0.568045 |
5dd8166d000d6fb32b22680bae10588cfb412058 | 1,695 | import Glibc
public struct AddrInfoIterator: IteratorProtocol {
var addrinfo: UnsafeMutablePointer<addrinfo>?
init(_ addrinfo: UnsafeMutablePointer<addrinfo>?) {
self.addrinfo = addrinfo
}
public mutating func next() -> UnsafeMutablePointer<addrinfo>? {
let addr = addrinfo
addrinfo = addrinfo?.pointee.ai_next
return addr
}
}
public class AddrInfo: Sequence {
let addr: UnsafeMutablePointer<addrinfo>?
public init(_ addr: UnsafeMutablePointer<addrinfo>?) {
self.addr = addr
}
public func makeIterator() -> AddrInfoIterator {
return AddrInfoIterator(self.addr)
}
deinit {
freeaddrinfo(addr)
}
}
public func getAddrinfo(
host: String, port: UInt16, family: SockFamily = SockFamily.inet,
type: SockType = SockType.tcp, proto: SockProt = SockProt.tcp, flags: Int32 = 0
) throws -> AddrInfo {
var hints = addrinfo()
// Support both IPv4 and IPv6
hints.ai_family = family.rawValue
hints.ai_socktype = type.rawValue
hints.ai_flags = flags
hints.ai_protocol = proto.rawValue
var result: UnsafeMutablePointer<addrinfo>?
let res = getaddrinfo(host, "\(port)", &hints, &result)
guard res >= 0 else {
throw GooseError.error()
}
return AddrInfo(result)
}
extension addrinfo {
public var family: SockFamily {
return SockFamily(fromRawValue: self.ai_family)
}
public var type: SockType {
return SockType(fromRawValue: self.ai_socktype)
}
public var prot: SockProt {
return SockProt(fromRawValue: self.ai_protocol)
}
public var flags: Int32 {
return self.ai_flags
}
}
| 24.214286 | 83 | 0.661357 |
76b21297b19a8fa00da2330b7e43361148c9ab8b | 1,857 | //
// ClockViewController.swift
// todayWidgetDemo
//
// Created by Christina Moulton on 2015-05-21.
// Copyright (c) 2015 Teak Mobile Inc. All rights reserved.
//
import UIKit
class ClockViewController: UIViewController {
var timeLabel: UILabel?
var timer: NSTimer?
let INTERVAL_SECONDS = 0.2
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// set up date formatter since it's expensive to keep creating them
self.dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
self.dateFormatter.timeStyle = NSDateFormatterStyle.LongStyle
// create and add label to display time
timeLabel = UILabel(frame: self.view.frame)
updateTimeLabel(nil) // to initialize the time displayed
// style the label a little: multiple lines, center, large text
timeLabel?.numberOfLines = 0 // allow it to wrap on to multiple lines if needed
timeLabel?.textAlignment = .Center
timeLabel?.font = UIFont.systemFontOfSize(28.0)
self.view.addSubview(timeLabel!)
// Timer will tick ever 1/5 of a second to tell the label to update the display time
timer = NSTimer.scheduledTimerWithTimeInterval(INTERVAL_SECONDS, target: self, selector: "updateTimeLabel:", userInfo: nil, repeats: true)
}
func updateTimeLabel(timer: NSTimer!) {
if let label = timeLabel {
// get the current time
let now = NSDate()
// convert time to a string for display
let dateString = dateFormatter.stringFromDate(now)
label.text = dateString
// set the dateString in the shared data store
let defaults = NSUserDefaults(suiteName: "group.teakmobile.grokswift.todayWidget")
defaults?.setObject(dateString, forKey: "timeString")
// tell the defaults to write to disk now
defaults?.synchronize()
}
}
}
| 33.160714 | 142 | 0.708131 |
bb01dc887730a264e21ab816e794146af4917ac5 | 678 | //
// Extensions.swift
// VoiceOverlay
//
// Created by Guy Daher on 25/06/2018.
// Copyright © 2018 Algolia. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
public func dismissMe(animated: Bool, completion: (()->())? = nil) {
var count = 0
if let c = self.navigationController?.viewControllers.count {
count = c
}
if count > 1 {
self.navigationController?.popViewController(animated: animated)
if let handler = completion {
handler()
}
} else {
dismiss(animated: animated, completion: completion)
}
}
}
| 24.214286 | 76 | 0.579646 |
e06327e4a73f08c6d3bdb27683443f7311b6cd60 | 6,612 | //
// Created by VT on 20.07.18.
// Copyright © 2018 strike65. All rights reserved.
/*
Copyright (2017-2019) strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
#if os(macOS) || os(iOS)
import os.log
#endif
extension SSProbDist {
/// Logistic
public enum Logistic {
/// Returns the Logit for a given p
/// - Parameter p: p
/// - Throws: SSSwiftyStatsError if p <= 0 || p >= 1
public static func logit<FPT: SSFloatingPoint & Codable>(p: FPT) throws -> FPT {
if p <= 0 || p >= 1 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("p is expected to be >= 0 or <= 1.0 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
return SSMath.log1p1(p / (1 - p))
}
/// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Logistic distribution.
/// - Parameter mean: mean
/// - Parameter b: Scale parameter b
/// - Throws: SSSwiftyStatsError if b <= 0
public static func para<FPT: SSFloatingPoint & Codable>(mean: FPT, scale b: FPT) throws -> SSProbDistParams<FPT> {
if b <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter b is expected to be > 0 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>()
result.mean = mean
result.variance = SSMath.pow1(b, 2) * SSMath.pow1(FPT.pi, 2) / 3
result.kurtosis = Helpers.makeFP(4.2)
result.skewness = 0
return result
}
/// Returns the pdf of the Logistic distribution.
/// - Parameter x: x
/// - Parameter mean: mean
/// - Parameter b: Scale parameter b
/// - Throws: SSSwiftyStatsError if b <= 0
public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, mean: FPT, scale b: FPT) throws -> FPT {
if b <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter b is expected to be > 0 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
let expr1: FPT = SSMath.exp1(-(x - mean) / b)
let expr2: FPT = SSMath.exp1(-(x - mean) / b)
let result: FPT = expr1 / (b * SSMath.pow1(1 + expr2, 2))
return result
}
/// Returns the cdf of the Logistic distribution.
/// - Parameter x: x
/// - Parameter mean: mean
/// - Parameter b: Scale parameter b
/// - Throws: SSSwiftyStatsError if b <= 0
public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, mean: FPT, scale b: FPT) throws -> FPT {
if b <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter b is expected to be > 0 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var ex1: FPT
var ex2: FPT
var ex3: FPT
ex1 = x - mean
ex2 = ex1 / b
ex3 = FPT.one + SSMath.tanh1(FPT.half * ex2)
let result = FPT.half * ex3
return result
}
/// Returns the quantile of the Logistic distribution.
/// - Parameter p: p
/// - Parameter mean: mean
/// - Parameter b: Scale parameter b
/// - Throws: SSSwiftyStatsError if b <= 0 || p < 0 || p > 1
public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, mean: FPT, scale b: FPT) throws -> FPT {
if b <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter b is expected to be > 0 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p < 0 || p > 1 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("p is expected to be >= 0 and <= 1 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var ex1: FPT
var ex2: FPT
let result: FPT
if p.isZero {
return -FPT.infinity
}
else if abs(1 - p) < FPT.ulpOfOne {
return FPT.infinity
}
else {
ex1 = FPT.minusOne + SSMath.reciprocal(p)
ex2 = b * SSMath.log1(ex1)
result = mean - ex2
return result
}
}
}
}
| 38.44186 | 135 | 0.505898 |
decd788848e309cfded7a4752320e78ed13ef5c8 | 1,069 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "CommonLibrary",
platforms: [.iOS(.v11)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "CommonLibrary",
targets: ["CommonLibrary"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "CommonLibrary",
dependencies: []),
.testTarget(
name: "CommonLibraryTests",
dependencies: ["CommonLibrary"]),
]
)
| 35.633333 | 117 | 0.624883 |
dedd1b2713884062423a812022492e92b54df606 | 357 | //
// CHConnectionDelegate.swift
// Channelize-API
//
// Created by Ashish-BigStep on 1/24/19.
// Copyright © 2019 Channelize. All rights reserved.
//
import Foundation
public protocol CHConnectionDelegate {
func didStartReconnection()
func didServerConnected()
func didServerDisconnected()
func didConnectionFailed()
}
| 17.85 | 53 | 0.703081 |
332b430b1c399b3296a6bd6e8f9e22066eaed953 | 1,651 | //
// SeedableArray.swift
// NumericalTests
//
// Created by Adam Roberts on 11/3/19.
//
import Foundation
/// A single draw of a random number
///
/// Uses `drand48()` which can be seeded. Optionally accepts a range, otherwise by default
/// will draw from [0,1].
func draw(range: ClosedRange<Double> = 0.0...1.0) -> Double {
return range.lowerBound + drand48() * (range.upperBound - range.lowerBound)
}
/// A reproducible array of random numbers
///
/// Requires a seed to give reproducibiity. The intended use is for producing test cases. Should not
/// be used for cryptography. Can choose whether to include negative numbers and the range of
/// exponents. By default it gives an array drawn from [-1,1].
func randomArray(seed: Int, n: UInt, exponentRange: ClosedRange<Double> = 0.0...0.0, signed: Bool = true) -> [Double] {
srand48(seed)
let c: [Double] = (0..<n).map { _ in
let sign = signed ? (drand48() > 0.5 ? 1.0 : -1.0) : 1.0
let significand = drand48()
let exponent = pow(10.0, draw(range: exponentRange).rounded())
return sign * significand * exponent
}
return c
}
extension Array {
/// Reproducible shuffle
///
/// Requires a seed to give reproducibility. The intended use is for producing test cases.
/// This simple implementation has some non-zero risk of collisions causing ambiguity in
/// the sort. Risk should be low for small (less than 1M element) arrays.
func shuffled(seed: Int) -> Array<Element> {
let rand = randomArray(seed: seed, n: UInt(count))
return zip(rand,self).sorted { $0.0 < $1.0 }.map { $0.1 }
}
}
| 35.12766 | 119 | 0.653543 |
11d91651dbe97d84b7d052d1d5ed60af93d6529d | 2,802 | //
// Extentions.swift
// gSwitch
//
// Created by Cody Schrank on 4/18/18.
// Copyright © 2018 CodySchrank. All rights reserved.
//
import Cocoa
@IBDesignable
class HyperlinkTextField: NSTextField {
@IBInspectable var href: String = ""
override func awakeFromNib() {
super.awakeFromNib()
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
self.attributedStringValue = NSAttributedString(string: self.stringValue, attributes: attributes)
}
override func mouseDown(with theEvent: NSEvent) {
NSWorkspace.shared.open(URL(string: href)!)
}
}
@IBDesignable
class HyperlinkTextFieldNoURL: NSTextField {
@IBInspectable var href: String = ""
override func awakeFromNib() {
super.awakeFromNib()
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
self.attributedStringValue = NSAttributedString(string: self.stringValue, attributes: attributes)
}
}
/*
Checks to see if the string is contained in the group of strings
- returns:
true if the string was in the group, else false
*/
extension String {
func any(_ group: [String]) -> Bool {
var atLeastOneInGroup = false
for str in group {
if self.contains(str) {
atLeastOneInGroup = true
break
}
}
return atLeastOneInGroup
}
}
/*
Checks to see if any string is contained in the group of strings
- returns:
true if any string was in the group, else false
*/
extension Array where Element == String {
func any(_ group: [String]) -> Bool {
var anyInGroup = false
for str in group {
if str.any(self) {
anyInGroup = true
break
}
}
return anyInGroup
}
}
class OnlyIntegerValueFormatter: NumberFormatter {
override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
// Ability to reset your field (otherwise you can't delete the content)
// You can check if the field is empty later
if partialString.isEmpty {
return true
}
// Optional: limit input length
/*
if partialString.characters.count>3 {
return false
}
*/
// Actual check
return Int(partialString) != nil
}
}
| 25.706422 | 219 | 0.608851 |
9ba34066ea815fc839de4387d46ef8eb017428c2 | 2,194 | //
// RequestAdapterImp.swift
// NetworkStack
//
// Created by Evgeniy on 10/11/2018.
// Copyright © 2018 Evgeniy. All rights reserved.
//
import Foundation
public final class RequestAdapterImp: RequestAdapter {
// MARK: - Members
private let endpoint: String
// MARK: - Interface
public static func adapt(_ endpoint: String) -> URL? {
return URL(string: endpoint)
}
public static func adapt(_ parts: [String]) -> URL? {
let endpoint = parts.joined()
return URL(string: endpoint)
}
// ====
public func adapt(_ part: String) -> URL? {
guard var adaptedURL = URL(string: endpoint) else {
return nil
}
adaptedURL.appendPathComponent(part)
return adaptedURL
}
public func adapt(_ parts: [String]) -> URL? {
guard var adaptedURL = URL(string: endpoint) else {
return nil
}
for part in parts {
adaptedURL.appendPathComponent(part)
}
return adaptedURL
}
// ====
public func adapt(_ part: String, query: [QueryItem]) -> URL? {
guard
let adapted = adapt(part),
var components = URLComponents(url: adapted, resolvingAgainstBaseURL: false) else {
return nil
}
components.queryItems = makeQueryItems(from: query)
return components.url
}
public func adapt(_ parts: [String], query: [QueryItem]) -> URL? {
guard
let adapted = adapt(parts),
var components = URLComponents(url: adapted, resolvingAgainstBaseURL: false) else {
return nil
}
components.queryItems = makeQueryItems(from: query)
return components.url
}
private func makeQueryItems(from query: [QueryItem]) -> [URLQueryItem] {
let result = query.map { (item: QueryItem) -> URLQueryItem in
let fieldValue = item.values.map { $0.value }.joined(separator: ",")
return URLQueryItem(name: item.field.value, value: fieldValue)
}
return result
}
// MARK: - Init
public init(endpoint: String) {
self.endpoint = endpoint
}
}
| 24.651685 | 95 | 0.589335 |
012d563b2cda3b829f6e21d1c31924243b32c0b8 | 681 | import XCTest
class A {
func testLooksValidIgnore0() {}
class B: XCTestCase {}
}
extension A {
class C: XCTestCase {}
}
extension A.B {
func testIsValid() throws {}
class C: XCTestCase {}
}
extension A {
func testLooksValidIgnore1() {}
}
class F: XCTestCase {}
enum D {
class A: XCTestCase {}
// test discovers that B inherits from D.A which is valid
// if B is nested,
// look for A that would also be nested
// if available, use that to compare
class B: A {}
class C: XCTestCase {
func testValid() {}
}
class D: F {}
}
extension D {
func testLooksValidIgnore2() {}
}
protocol Bar {}
class E: Bar {}
| 16.214286 | 61 | 0.60793 |
610e748994eef755d3162c2aebcc8ff67ad8e80e | 2,545 | //
// ViewController.swift
// RealmTest
//
// Created by Bret Smith on 4/23/15.
// Copyright (c) 2015 Exemine. All rights reserved.
//
import UIKit
import Realm
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Query using an NSPredicate object
let predicate = NSPredicate(format: "title BEGINSWITH %@", "Booya")
var challenges = Challenge.objectsWithPredicate(predicate)
if challenges == nil || challenges.count == 0 {
let tcChallenge = TotalCountChallenge()
tcChallenge.title = "Booya Total Count Challenge"
tcChallenge.totalCountGoal = 1_000_000
let rChallenge = RecurringChallenge()
rChallenge.title = "Booya Recurring Challenge"
rChallenge.recurranceType = .Weekly
rChallenge.totalCountGoal = 2_000_000
let realm = RLMRealm.defaultRealm()
// You only need to do this once (per thread)
// Add to the Realm inside a transaction
realm.beginWriteTransaction()
realm.addObject(tcChallenge)
realm.addObject(rChallenge)
realm.commitWriteTransaction()
}
challenges = Challenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
for challenge in challenges {
let c = challenge as! Challenge
println("\(c.title)")
}
} else {
println("No Challenges found")
}
challenges = TotalCountChallenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
for challenge in challenges {
let c = challenge as! Challenge
println("TotalCountChallenge: \(c.title)")
}
} else {
println("No Total Count Challenges found")
}
challenges = RecurringChallenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
for challenge in challenges {
let c = challenge as! Challenge
println("RecurringChallenge \(c.title)")
}
} else {
println("No Recurring Challenges found")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 31.419753 | 75 | 0.573674 |
e8f0f807bd964f11dc02016b7a532dcb7cbb18a1 | 2,692 | /*
Copyright (c) 2017 Swift Models Generated from JSON powered by http://www.json4swift.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
/* For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar */
public class Likes {
public var count : Int?
public var groups : Array<Group>?
public var summary : String?
/**
Returns an array of models based on given dictionary.
Sample usage:
let likes_list = Likes.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
- parameter array: NSArray from JSON dictionary.
- returns: Array of Likes Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [Likes]
{
var models:[Likes] = []
for item in array
{
models.append(Likes(dictionary: item as! NSDictionary)!)
}
return models
}
/**
Constructs the object based on the given dictionary.
Sample usage:
let likes = Likes(someDictionaryFromJSON)
- parameter dictionary: NSDictionary from JSON.
- returns: Likes Instance.
*/
required public init?(dictionary: NSDictionary) {
count = dictionary["count"] as? Int
if (dictionary["groups"] != nil) { groups = Group.modelsFromDictionaryArray(array: dictionary["groups"] as! NSArray) }
summary = dictionary["summary"] as? String
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.count, forKey: "count")
dictionary.setValue(self.summary, forKey: "summary")
return dictionary
}
}
| 36.378378 | 460 | 0.733655 |
2164ad3172b37565ed70ac9954e841202f0e9830 | 242 | // 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 {
protocol A {
class A<f : d {
}
typealias e : A
class d: A<Int>
| 22 | 87 | 0.72314 |
7247e977519ef6cc72c8dfbf2c8b61299cce6e54 | 166 | //
// Review.swift
// Budi
//
// Created by 최동규 on 2022/01/12.
//
import Foundation
struct Review: Codable {
let title: String
let description: String
}
| 11.857143 | 33 | 0.638554 |
1a05e5de139683b985d417b8c00e27c69cc93b9c | 9,415 | //
// CombineScansOperation.swift
// Magazine Scan Combiner
//
// Created by Prachi Gauriar on 7/3/2016.
// Copyright © 2016 Prachi Gauriar.
//
// 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 Cocoa
/// The types of errors that can occur during the execution of the operation.
enum CombineScansError : Error {
/// Indicates that the input PDF located at the associated `URL` could not be opened.
case couldNotOpenFileURL(URL)
/// Indicates that an output PDF could not be created at the associated `URL`.
case couldNotCreateOutputPDF(URL)
}
/// `CombineScansOperation` is an `Operation` subclass that combines the pages of two PDFs into a
/// single new PDF. `CombineScansOperations` are meant to run concurrently in an operation queue,
/// although they can be run synchronously by simply invoking an instance’s `start` method.
///
/// ## Page Order in the Output PDF
///
/// The two input PDFs are combined in a peculiar way: the pages of the second PDF are first
/// reversed, and then interleaved with the pages of the first PDF. For example, suppose the first
/// PDF has pages *P1*, *P2*, …, *Pm*, and the second PDF has pages *Q1*, *Q2*, …, *Qn*. Then the
/// output PDF will have the pages *P1*, *Qn*, *P2*, …, *Q2*, *Pm*, *Q1*.
///
/// ## Monitoring Progress
///
/// To monitor an operation’s progress, access its `progress` property. That property’s
/// `totalUnitCount` is the total number of pages that will be in the output PDF; its
/// `completedUnitCount` is the number of pages that have been written to the output PDF so far.
class CombineScansOperation : ConcurrentProgressReportingOperation {
/// The file URL of the PDF whose contents are the front pages of a printed work.
let frontPagesPDFURL: URL
/// The file URL of the PDF whose contents are the back pages of a printed work in reverse order.
let reversedBackPagesPDFURL: URL
/// The file URL at which to store the output PDF.
let outputPDFURL: URL
/// Contains an error that occurred during execution of the instance. If nil, no error occurred.
/// If this is set, the operation finished unsuccessfully.
private(set) var error: CombineScansError?
/// Initializes a newly created `CombineScansOperation` instance with the specified front pages PDF
/// URL, reversed back pages PDF URL, and output PDF URL.
///
/// - parameter frontPagesPDFURL: The file URL of the PDF whose contents are the front pages of
/// a printed work.
/// - parameter reversedBackPagesPDFURL: The file URL of the PDF whose contents are the back pages
/// of a printed work in reverse order.
/// - parameter outputPDFURL: The file URL at which to store the output PDF.
init(frontPagesPDFURL: URL, reversedBackPagesPDFURL: URL, outputPDFURL: URL) {
self.frontPagesPDFURL = frontPagesPDFURL
self.reversedBackPagesPDFURL = reversedBackPagesPDFURL
self.outputPDFURL = outputPDFURL
super.init()
progress.cancellationHandler = { [unowned self] in
self.cancel()
}
}
override func start() {
// If we’re finished or canceled, return immediately
guard !isFinished && !isCancelled else {
return
}
isExecuting = true
// However we exit, we want to mark ourselves as no longer executing
defer { isFinished = true }
// If we couldn’t open the front pages PDF, set our error, finish, and exit
guard let frontPagesDocument = CGPDFDocument(frontPagesPDFURL as CFURL) else {
error = .couldNotOpenFileURL(frontPagesPDFURL)
return
}
// If we couldn’t open the reversed back pages PDF, set our error, finish, and exit
guard let reversedBackPagesDocument = CGPDFDocument(reversedBackPagesPDFURL as CFURL) else {
error = .couldNotOpenFileURL(reversedBackPagesPDFURL)
return
}
// If we couldn’t create the output PDF context, set our error, finish, and exit
guard let outputPDFContext = CGContext(outputPDFURL as CFURL, mediaBox: nil, nil) else {
error = .couldNotCreateOutputPDF(outputPDFURL)
return
}
let pageCount = frontPagesDocument.numberOfPages + reversedBackPagesDocument.numberOfPages
progress.totalUnitCount = Int64(pageCount)
for page in ScannedPageSequence(frontPagesDocument: frontPagesDocument, reversedBackPagesDocument: reversedBackPagesDocument) {
guard !isCancelled else {
break
}
// Start a new page in our output, get the contents of the page from our input, write that page to our output
var mediaBox = page.getBoxRect(.mediaBox)
outputPDFContext.beginPage(mediaBox: &mediaBox)
outputPDFContext.drawPDFPage(page)
outputPDFContext.endPage()
progress.completedUnitCount += 1
}
outputPDFContext.closePDF()
// If we were canceled, try to remove the output PDF, but don’t worry about it if we can’t
if isCancelled {
do {
try FileManager.default.removeItem(at: outputPDFURL)
} catch {
}
}
}
}
/// Instances of `ScannedPagesSequence` generate a sequence of `CGPDFPage` objects from two PDFs.
/// The order of the pages is that described in the `CombineScansOperation` class documentation.
private struct ScannedPageSequence : Sequence, IteratorProtocol {
/// Indicates whether the next page should come from the front pages PDF.
var isNextPageFromFront: Bool
/// The iterator for pages from the front pages PDF document.
var frontPageIterator: PDFDocumentPageIterator
/// The iterator for pages from the back pages PDF document. This iterator returns pages
/// in reverse order.
var backPageIterator: PDFDocumentPageIterator
/// Initializes a newly created `ScannedPagesSequence` instance with the specified front pages PDF
/// document and reversed back pages PDF document.
init(frontPagesDocument : CGPDFDocument, reversedBackPagesDocument: CGPDFDocument) {
isNextPageFromFront = true
let frontPageNumbers = 1 ..< (frontPagesDocument.numberOfPages + 1)
let backPageNumbers = (1 ..< (reversedBackPagesDocument.numberOfPages + 1)).reversed()
frontPageIterator = PDFDocumentPageIterator(document: frontPagesDocument, pageNumbers: frontPageNumbers)
backPageIterator = PDFDocumentPageIterator(document: reversedBackPagesDocument, pageNumbers: backPageNumbers)
}
mutating func next() -> CGPDFPage? {
defer { isNextPageFromFront = !isNextPageFromFront }
if isNextPageFromFront {
return frontPageIterator.next() ?? backPageIterator.next()
} else {
return backPageIterator.next() ?? frontPageIterator.next()
}
}
}
/// Instances of `PDFDocumentPageIterator` iterate over a sequence of `CGPDFPage` objects from a single PDF
/// document using a sequence of page numbers specified at initialization time. For example, an iterator
/// initialized like
///
/// ```
/// var iterator = PDFDocumentPageIterator(document, [1, 3, 2, 4, 4])
/// ```
///
/// would return the 1st, 3rd, 2nd, 4th, and 4th pages of the specified PDF document.
private struct PDFDocumentPageIterator : IteratorProtocol {
/// The PDF document from which the instance gets pages.
let document: CGPDFDocument
/// An Int iterator that returns the next page number to get from the PDF document.
var pageNumberIterator: AnyIterator<Int>
/// Initializes a newly created `PDFDocumentPageIterator` with the specified document and page numbers.
/// - parameter document: The PDF document from which the instance gets pages.
/// - parameter pageNumbers: The sequence of page numbers that the iterator should use when getting pages.
init<IntSequence: Sequence>(document: CGPDFDocument, pageNumbers: IntSequence) where IntSequence.Iterator.Element == Int {
self.document = document
pageNumberIterator = AnyIterator(pageNumbers.makeIterator())
}
mutating func next() -> CGPDFPage? {
guard let pageNumber = pageNumberIterator.next() else {
return nil
}
return document.page(at: pageNumber)
}
}
| 43.188073 | 135 | 0.699628 |
392c5951637a2cc1b7753024aa540225832b82fa | 4,314 | //
// ObserverTests.swift
//
import XCTest
import Chaining
class ObserverTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testInvalidate() {
// AnyObserverのInvalidateの動作
let mainNotifier = Notifier<Int>()
let subNotifier = Notifier<Int>()
var received: [Int] = []
let observer =
mainNotifier.chain()
.merge(subNotifier.chain())
.do { received.append($0) }
.end()
mainNotifier.notify(value: 1)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0], 1)
subNotifier.notify(value: 2)
XCTAssertEqual(received.count, 2)
XCTAssertEqual(received[1], 2)
// invalidateされると送信しない
observer.invalidate()
mainNotifier.notify(value: 3)
XCTAssertEqual(received.count, 2)
subNotifier.notify(value: 4)
XCTAssertEqual(received.count, 2)
}
func testObserverPool() {
// ObserverPoolの動作
let pool = ObserverPool()
let notifier = Notifier<Int>()
let holder = ValueHolder<String>("0")
var notifierReceived: [Int] = []
var holderReceived: [String] = []
// ObserverPoolにObserverを追加
pool.add(notifier.chain().do { notifierReceived.append($0) }.end())
pool.add(holder.chain().do { holderReceived.append($0) }.sync())
XCTAssertEqual(holderReceived.count, 1)
XCTAssertEqual(holderReceived[0], "0")
notifier.notify(value: 1)
holder.value = "2"
XCTAssertEqual(notifierReceived.count, 1)
XCTAssertEqual(notifierReceived[0], 1)
XCTAssertEqual(holderReceived.count, 2)
XCTAssertEqual(holderReceived[1], "2")
// invalidateを呼ぶと送信しない
pool.invalidate()
notifier.notify(value: 3)
holder.value = "4"
XCTAssertEqual(notifierReceived.count, 1)
XCTAssertEqual(holderReceived.count, 2)
}
func testObserverPoolRemove() {
// ObserverPoolから削除する
let pool = ObserverPool()
let notifier = Notifier<Int>()
let holder = ValueHolder<String>("0")
var notifierReceived: [Int] = []
var holderReceived: [String] = []
let notifierObserver = notifier.chain().do { notifierReceived.append($0) }.end()
let holderObserver = holder.chain().do { holderReceived.append($0) }.sync()
pool.add(notifierObserver)
pool.add(holderObserver)
XCTAssertEqual(holderReceived.count, 1)
XCTAssertEqual(holderReceived[0], "0")
notifier.notify(value: 1)
holder.value = "2"
XCTAssertEqual(notifierReceived.count, 1)
XCTAssertEqual(notifierReceived[0], 1)
XCTAssertEqual(holderReceived.count, 2)
XCTAssertEqual(holderReceived[1], "2")
// 削除された方はpoolでinvalidateされなくなる
pool.remove(holderObserver)
pool.invalidate()
notifier.notify(value: 3)
holder.value = "4"
XCTAssertEqual(notifierReceived.count, 1)
XCTAssertEqual(holderReceived.count, 3)
XCTAssertEqual(holderReceived[2], "4")
}
func testAddTo() {
let pool = ObserverPool()
let notifier = Notifier<Int>()
var received: [Int] = []
notifier.chain()
.do { received.append($0) }
.end().addTo(pool)
notifier.notify(value: 1)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0], 1)
pool.invalidate()
notifier.notify(value: 2)
XCTAssertEqual(received.count, 1)
}
func testInvalidateOnDo() {
let notifier = Notifier<Int>()
var observer: AnyObserver?
observer = notifier.chain().do { _ in
observer?.invalidate()
}.end()
notifier.notify(value: 0)
}
}
| 26.466258 | 88 | 0.544043 |
1140f11337ba99f49ab737e4158df33c9e598196 | 572 | // main.swift
//
// 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
//
// -----------------------------------------------------------------------------
func foo(_ x: Int, y: Int, z: Int) -> Int {
return x + y - z
}
func main() {
print(foo(5, y: 31, z: 12))
}
main()
| 27.238095 | 80 | 0.583916 |
7686070cef38ff6fb4986b01f6378c6b4ab5aee9 | 4,913 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import Beagle
import SnapshotTesting
// swiftlint:disable force_unwrapping
final class NetworkCacheTests: XCTestCase {
private lazy var subject = NetworkCache(dependencies: dependencies)
private lazy var dependencies = BeagleScreenDependencies(cacheManager: cacheSpy)
private let cacheSpy = CacheManagerSpy()
private var (id, aHash, maxAge) = ("id", "123", 15)
private let data = "Cache Test".data(using: .utf8)!
private lazy var reference = CacheReference(identifier: id, data: data, hash: id)
private lazy var completeHeaders = [
"Beagle-Hash": aHash,
"Cache-Control": "max-age=\(maxAge)"
]
func testCacheControlHeaderShouldCacheTheResponse() {
// Given
let urlResponse = HTTPURLResponse(url: URL(string: id)!, statusCode: 200, httpVersion: nil, headerFields: completeHeaders)!
// When
subject.saveCacheIfPossible(
url: id,
response: .init(data: data, response: urlResponse)
)
// Then
let cache = cacheSpy.references.first!.cache
XCTAssert(cache.identifier == id)
XCTAssert(cache.data == data)
XCTAssert(cache.hash == aHash)
XCTAssert(cache.maxAge == maxAge)
}
func testShouldFailMetaDataWithoutHash() {
// Given
let headers = [AnyHashable: Any]()
// When
let cache = subject.getMetaData(from: headers)
// Then
XCTAssert(cache == nil)
}
func testShouldHaveMetaData() {
// When
let cache = subject.getMetaData(from: completeHeaders)
// Then
XCTAssert(cache?.hash == aHash)
XCTAssert(cache?.maxAge == maxAge)
}
func testMetaDataWithInvalidMaxAge() {
// Given
let invalidMaxAge = "notNumber"
completeHeaders["Cache-Control"] = invalidMaxAge
// When
let cache = subject.getMetaData(from: completeHeaders)
// Then
XCTAssert(cache?.hash == aHash)
XCTAssert(cache?.maxAge == nil)
}
func testWhenDataNotCached() {
// When
let cache = subject.checkCache(identifiedBy: id, additionalData: nil)
// Then
XCTAssert(cache == .dataNotCached)
}
func testWhenValidCachedData() {
// Given
cacheSpy.references.append(.init(cache: reference, isValid: true))
// When
let cache = subject.checkCache(identifiedBy: id, additionalData: nil)
// Then
XCTAssert(cache == .validCachedData(data))
}
func testCacheDisabled() {
// Given
dependencies.cacheManager = nil
// When
let cache = subject.checkCache(identifiedBy: "id", additionalData: nil)
// Then
XCTAssert(cache == .disabled)
}
func testInvalidCachedData() {
// Given
cacheSpy.references.append(.init(cache: reference, isValid: false))
// When
let cache = subject.checkCache(identifiedBy: id, additionalData: nil)
// Then
XCTAssert(cache == .invalidCachedData(data: data, additional: nil))
}
func testInvalidCachedDataWithHash() {
// Given
cacheSpy.references.append(.init(cache: reference, isValid: false))
// When
let cache = subject.checkCache(identifiedBy: id, additionalData: .Http(httpData: nil))
// Then
let expected: NetworkCache.CacheCheck = .invalidCachedData(
data: data,
additional: .Http(httpData: nil, headers: [subject.cacheHashHeader: id])
)
XCTAssert(cache == expected)
}
}
extension NetworkCache.CacheCheck {
public static func == (lhs: NetworkCache.CacheCheck, rhs: NetworkCache.CacheCheck) -> Bool {
switch (lhs, rhs) {
case let (.validCachedData(data1), .validCachedData(data2)):
return data1 == data2
case (.dataNotCached, .dataNotCached),
(.disabled, .disabled):
return true
case let (
.invalidCachedData(data: data1, additional: add1),
.invalidCachedData(data: data2, additional: add2)
):
return data1 == data2 && add1?.headers == add2?.headers
default:
return false
}
}
}
| 29.071006 | 131 | 0.626705 |
299b31f6b303c6fe49779f9a8423cb12d5754cce | 158 | //
// File.swift
// temadagar
//
// Created by Alvar Lagerlöf on 11/10/16.
// Copyright © 2016 Alvar Lagerlöf. All rights reserved.
//
import Foundation
| 15.8 | 57 | 0.677215 |
76ab6ac8b04ced661aacd62adcbd0946a2b08628 | 443 | //
// DeploymentEnvironment.swift
// BucketSDK
//
// Created by Ryan Coyne on 4/6/18.
//
@objc public enum DeploymentEnvironment: Int {
case production, development
var url: URL {
switch self {
case .production:
return URL(string: "https://bucketthechange.com/api")!
case .development:
return URL(string: "https://sandboxretailerapi.bucketthechange.com/api")!
}
}
}
| 22.15 | 85 | 0.609481 |
e9a5cc12d2c6bc54359de879be06b59c13642ba3 | 6,501 | //
// SDL.swift
// SwiftSDL2
//
// Created by sunlubo on 2019/1/29.
//
import CSDL2
public enum SDL {
/// This function initializes the subsystems specified by `flags`.
///
/// - Throws: SDLError
public static func initialize(flags: InitFlag) throws {
try throwIfFail(SDL_Init(flags.rawValue))
}
/// This function cleans up all initialized subsystems. You should call it upon all exit conditions.
public static func quit() {
SDL_Quit()
}
/// Set a hint with a specific priority.
///
/// - Parameters:
/// - value: The value of the hint variable.
/// - name: The hint to set.
/// - priority: The `HintPriority` level for the hint.
/// - Returns: `true` if successful, otherwise `false`.
@discardableResult
public static func setHint(
_ value: String, forName name: String, priority: HintPriority = .normal
) -> Bool {
return SDL_SetHintWithPriority(name, value, SDL_HintPriority(priority.rawValue)) == SDL_TRUE
}
/// Get the value of a hint.
///
/// - Parameter name: the hint to query
/// - Returns: Returns the string value of a hint or NULL if the hint isn't set.
public static func hint(forName name: String) -> String? {
return String(cString: SDL_GetHint(name))
}
public static func env(forName name: String) -> String? {
return String(cString: SDL_getenv(name))
}
@discardableResult
public static func setEnv(_ value: String, forName name: String, overwrite: Bool = true) -> Bool {
return SDL_setenv(name, value, overwrite ? 1 : 0) == 1
}
/// Wait a specified number of milliseconds before returning.
public static func delay(ms: Int) {
SDL_Delay(UInt32(ms))
}
/// Returns the name of the currently initialized video driver.
public static var currentVideoDriver: String? {
return String(cString: SDL_GetCurrentVideoDriver())
}
/// Get the number of video drivers compiled into SDL.
public static var videoDriverCount: Int {
return Int(SDL_GetNumVideoDrivers())
}
/// Get the name of a built in video driver.
///
/// - Note: The video drivers are presented in the order in which they are
/// normally checked during initialization.
///
/// - Parameter index: the index of a video driver
/// - Returns: Returns the name of the video driver with the given index.
public static func videoDriver(at index: Int) -> String? {
return String(cString: SDL_GetVideoDriver(Int32(index)))
}
/// Returns the number of available video displays.
public static var videoDisplayCount: Int {
return Int(SDL_GetNumVideoDisplays())
}
/// Get the name of a display in UTF-8 encoding.
///
/// - Parameter index: the index of display from which the name should be queried
/// - Returns: The name of a display, or `nil` for an invalid display index.
public static func videoDisplayName(at index: Int) -> String? {
return String(cString: SDL_GetDisplayName(Int32(index)))
}
}
// MARK: - SDL.InitFlag
extension SDL {
/// These are the flags which may be passed to `initSDL(flags:)`.
/// You should specify the subsystems which you will be using in your application.
public struct InitFlag: OptionSet {
/// timer subsystem
public static let timer = InitFlag(rawValue: SDL_INIT_TIMER)
/// audio subsystem
public static let audio = InitFlag(rawValue: SDL_INIT_AUDIO)
/// video subsystem, automatically initializes the events subsystem
public static let video = InitFlag(rawValue: SDL_INIT_VIDEO)
/// joystick subsystem, automatically initializes the events subsystem
public static let joyStick = InitFlag(rawValue: SDL_INIT_JOYSTICK)
/// haptic (force feedback) subsystem
public static let haptic = InitFlag(rawValue: SDL_INIT_HAPTIC)
/// controller subsystem, automatically initializes the joystick subsystem
public static let gameController = InitFlag(rawValue: SDL_INIT_GAMECONTROLLER)
/// events subsystem
public static let events = InitFlag(rawValue: SDL_INIT_EVENTS)
/// compatibility, this flag is ignored
public static let noParachute = InitFlag(rawValue: SDL_INIT_NOPARACHUTE)
///
public static let everything = [
.timer, .audio, .video, .events, .joyStick, .haptic, .gameController
] as InitFlag
public let rawValue: UInt32
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
}
// MARK: - SDL.Hint
extension SDL {
public struct Hint {
/// A variable controlling how 3D acceleration is used to accelerate the SDL screen surface.
///
/// SDL can try to accelerate the SDL screen surface by using streaming textures
/// with a 3D rendering engine. This variable controls whether and how this is done.
///
/// This variable can be set to the following values:
/// - `0`: Disable 3D acceleration.
/// - `1`: Enable 3D acceleration, using the default renderer.
/// - `X`: Enable 3D acceleration, using X where X is one of the valid rendering drivers.
/// (e.g. "direct3d", "opengl", etc.)
///
/// By default SDL tries to make a best guess for each platform whether to use acceleration or not.
public static let framebufferAcceleration = SDL_HINT_FRAMEBUFFER_ACCELERATION
/// A variable specifying which render driver to use.
///
/// If the application doesn't pick a specific renderer to use, this variable
/// specifies the name of the preferred renderer. If the preferred renderer
/// can't be initialized, the normal default renderer is used.
///
/// This variable is case insensitive and can be set to the following values:
/// - direct3d
/// - opengl
/// - opengles2
/// - opengles
/// - metal
/// - software
///
/// The default varies by platform, but it's the first one in the list that
/// is available on the current platform.
public static let renderDriver = SDL_HINT_RENDER_DRIVER
/// A variable controlling whether the OpenGL render driver uses shaders if they are available.
///
/// This variable can be set to the following values:
/// - `0`: Disable shaders
/// - `1`: Enable shaders
///
/// By default shaders are used if OpenGL supports them.
public static let renderOpenGLShaders = SDL_HINT_RENDER_OPENGL_SHADERS
}
/// Hint priorities.
public enum HintPriority: UInt32 {
/// low priority, used for default values
case `default`
/// medium priority
case normal
/// high priority
case override
}
}
| 34.579787 | 103 | 0.687433 |
1e3394b2c88630ac66d93cd6104149ad7e416a31 | 2,993 | //
// Day.swift
// UpcomingEvents
//
// Created by Tito Ciuro on 1/31/20.
// Copyright © 2020 Tito Ciuro. All rights reserved.
//
import Foundation
class Day {
let date: Date
private var _events: [Event]
var events: [Event] {
get { _events }
}
private var _isFiltered: Bool
var isFiltered: Bool {
get { _isFiltered }
}
lazy var eventConflicts: Set<Event> = {
return checkForConflicts(events: _events)
}()
init(date: Date, events: [Event]) {
self.date = date
self._isFiltered = false
self._events = events.sorted(by: { ev1, ev2 -> Bool in
ev1.start < ev2.start
})
}
/// Returns whether the event is in conlict with another one.
/// - Parameter event: the event to be tested.
func isEventInConflict(_ event: Event) -> Bool {
return eventConflicts.contains(event)
}
/// Checks whether the day contains conflicting events. Time complexity is O(nlogn) + O(n) -> O(nlogn) because the list has been sorted before the traversal.
func checkForConflicts(events: [Event]) -> Set<Event> {
guard events.count > 1, let firstEvent = events.first else { return [] }
var conflicts = Set<Event>()
var lastMaxEndTimeEvent = firstEvent
for i in 1 ..< events.count {
let event = events[i]
if lastMaxEndTimeEvent.end > event.start {
// Conflict detected!
conflicts.insert(lastMaxEndTimeEvent)
lastMaxEndTimeEvent.addConflict(event: event)
conflicts.insert(event)
event.addConflict(event: lastMaxEndTimeEvent)
lastMaxEndTimeEvent = lastMaxEndTimeEvent.end > event.end ? lastMaxEndTimeEvent : event
} else {
// No conflict, move on...
lastMaxEndTimeEvent = event
}
}
return conflicts
}
/// Sets the event list to contain the events that conflict with the main event.
/// - Parameter event: the main event to be filtered out and used to calculate conflicts with the other daily events.
@discardableResult func eventsConflicting(with mainEvent: Event) -> [Event] {
let mainDateInterval = NSDateInterval(start: mainEvent.start, end: mainEvent.end)
// Filter the main event + intersecting events
_events = _events.filter { event -> Bool in
if event == mainEvent { return false }
let eventDateInterval = NSDateInterval(start: event.start, end: event.end)
return mainDateInterval.intersects(eventDateInterval as DateInterval)
}
_isFiltered = true
return _events
}
}
extension Day: NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
let copy = Day(date: date, events: events)
return copy
}
}
| 30.85567 | 161 | 0.59138 |
90e5a1e58001e82231c7e02d00fc7fe95cb9fe9f | 1,430 | //
// BaseDao.swift
// ExchangeApp
//
// Created by Юрий Нориков on 27.11.2019.
// Copyright © 2019 norikoff. All rights reserved.
//
import Foundation
protocol BaseDao {
associatedtype T
associatedtype ID
/// Fetch all data from table
///
/// - Parameter completionHandler: return array of data or error
/// - Returns: error
func getAll(param: Any?, completion: @escaping (Result<[T]?, ErrorMessage>) -> Void)
/// Fetch data from table by id
///
/// - Parameters:
/// - identifier: fetch id
/// - completion: return array of data or error
/// - Returns: error
func get(identifier: ID, completion: @escaping (Result<T?, ErrorMessage>) -> Void )
/// Create table row
///
/// - Parameters:
/// - model: entity for save
/// - completion: return bool or error
/// - Returns: error
func save(model:T, completion: @escaping (Result<Bool, ErrorMessage>) -> Void)
/// Create table rows from array
///
/// - Parameters:
/// - model: array of objects
/// - completion: return bool or error
/// - Returns: return bool or error
func saveAll(model: [T], completion: @escaping (Result<Bool, ErrorMessage>) -> Void)
func clear(completion: @escaping (Result<Bool, ErrorMessage>) -> Void)
// func update( model:T ) -> Bool
// func delete( model:T ) -> Bool
}
| 27.5 | 88 | 0.592308 |
0e4f704f7195f1dd599427d0f6899eb9acc1a938 | 863 | public class iOSBlur: OperationGroup {
public var blurRadiusInPixels:Float = 48.0 { didSet { gaussianBlur.blurRadiusInPixels = blurRadiusInPixels } }
public var saturation:Float = 0.8 { didSet { saturationFilter.saturation = saturation } }
public var rangeReductionFactor:Float = 0.6 { didSet { luminanceRange.rangeReductionFactor = rangeReductionFactor } }
let saturationFilter = SaturationAdjustment()
let gaussianBlur = GaussianBlur()
let luminanceRange = LuminanceRangeReduction()
public override init() {
super.init()
({blurRadiusInPixels = 48.0})()
({saturation = 0.8})()
({rangeReductionFactor = 0.6})()
self.configureGroup{input, output in
input --> self.saturationFilter --> self.gaussianBlur --> self.luminanceRange --> output
}
}
}
| 39.227273 | 121 | 0.659328 |
f513ee59ce44c88422c2e80b605175de05d493ef | 2,482 | //
// SceneDelegate.swift
// CoreDataExample
//
// Created by thompsty on 1/19/21.
//
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| 46.830189 | 147 | 0.716761 |
7a790fce6fde5b93baaddcc37f95b294f792b886 | 4,839 | import Foundation
import UIKit
import Stripe
@objcMembers
@objc(TNSStripe)
public class TNSStripe: NSObject {
@nonobjc static func createConfig(config: NSDictionary?) -> PaymentSheet.Configuration {
var sheetConfig = PaymentSheet.Configuration()
if(config != nil){
let customerConfig = config!["customerConfig"] as? NSDictionary
if(customerConfig != nil){
let customer = PaymentSheet.CustomerConfiguration(id: customerConfig!["id"] as? String ?? "", ephemeralKeySecret: customerConfig!["ephemeralKey"] as? String ?? "")
sheetConfig.customer = customer
}
let merchantDisplayName = config!["merchantDisplayName"] as? String
if(merchantDisplayName != nil){
sheetConfig.merchantDisplayName = merchantDisplayName!
}
sheetConfig.allowsDelayedPaymentMethods = config!["allowsDelayedPaymentMethods"] as? Bool ?? false
let applePayConfig = config!["applePayConfig"] as? NSDictionary
if(applePayConfig != nil){
sheetConfig.applePay = PaymentSheet.ApplePayConfiguration(merchantId: applePayConfig!["merchantId"] as? String ?? "", merchantCountryCode: applePayConfig!["merchantCountryCode"] as? String ?? "")
}
let primaryButtonColor = config!["primaryButtonColor"] as? UIColor
if(primaryButtonColor != nil){
sheetConfig.primaryButtonColor = primaryButtonColor!
}
let defaultBillingDetails = config!["defaultBillingDetails"] as? NSDictionary
if(defaultBillingDetails != nil){
sheetConfig.defaultBillingDetails.name = defaultBillingDetails!["name"] as? String
sheetConfig.defaultBillingDetails.phone = defaultBillingDetails!["phone"] as? String
sheetConfig.defaultBillingDetails.email = defaultBillingDetails!["email"] as? String
let address = defaultBillingDetails!["address"] as? NSDictionary
if(address != nil){
sheetConfig.defaultBillingDetails.address.country = address!["country"] as? String
sheetConfig.defaultBillingDetails.address.line1 = address!["line1"] as? String
sheetConfig.defaultBillingDetails.address.line2 = address!["line2"] as? String
sheetConfig.defaultBillingDetails.address.postalCode = address!["postalCode"] as? String
sheetConfig.defaultBillingDetails.address.state = address!["state"] as? String
sheetConfig.defaultBillingDetails.address.city = address!["city"] as? String
}
}
if #available(iOS 13.0, *){
switch(config!["style"] as? String ?? "auto"){
case "dark":
sheetConfig.style = .alwaysDark
break
case "light":
sheetConfig.style = .alwaysLight
break
default:
sheetConfig.style = .automatic
break
}
}
sheetConfig.returnURL = config!["returnURL"] as? String
}
return sheetConfig
}
public static func presentWithPaymentIntent(_ clientSecret: String,_ config: NSDictionary,_ ctrl: UIViewController, _ callback: @escaping ((String, Error?) -> Void)){
let paymentSheet = PaymentSheet(paymentIntentClientSecret: clientSecret, configuration: createConfig(config: config))
paymentSheet.present(from: ctrl) { result in
switch(result){
case .completed:
callback("completed", nil)
case .canceled:
callback("canceled", nil)
case .failed(error: let error):
callback("failed", error)
}
}
}
public static func presentWithSetupIntent(_ clientSecret: String,_ config: NSDictionary,_ ctrl: UIViewController, _ callback: @escaping ((String, Error?) -> Void)){
let paymentSheet = PaymentSheet(setupIntentClientSecret: clientSecret, configuration: createConfig(config: config))
paymentSheet.present(from: ctrl) { result in
switch(result){
case .completed:
callback("completed", nil)
case .canceled:
callback("canceled", nil)
case .failed(error: let error):
callback("failed", error)
}
}
}
}
| 42.078261 | 211 | 0.566439 |
231cc476a9d7a1836885c3170b1fef0fc425e357 | 237 | @objcMembers
public class HDKConfig: NSObject {
public let appHostName: String
public let lang: String
public init(appHostName: String, lang: String) {
self.appHostName = appHostName
self.lang = lang
}
}
| 21.545455 | 52 | 0.670886 |
5b44d49c3e59432a090b2f42902f39274a8365d7 | 1,057 | //
// NotificationsView.swift
// ORTUS
//
// Created by Firdavs Khaydarov on 03/10/19.
// Copyright (c) 2019 Firdavs. All rights reserved.
//
import UIKit
class NotificationsView: UIView {
let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.backgroundView = nil
tableView.backgroundColor = .systemGroupedBackground
tableView.separatorStyle = .singleLine
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.rowHeight = UITableView.automaticDimension
return tableView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .systemBackground
addSubview(tableView)
tableView.snp.makeConstraints {
$0.top.bottom.equalToSuperview()
$0.left.right.equalTo(safeAreaLayoutGuide)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 27.102564 | 69 | 0.644276 |
29d7814a724140e8dcae9d2af30336797143b2d5 | 953 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
final class ___VARIABLE_moduleName___Wireframe: BaseWireframe {
// MARK: - Private properties -
// MARK: - Module setup -
init() {
let moduleViewController = ___VARIABLE_moduleName___ViewController()
super.init(viewController: moduleViewController)
let formatter = ___VARIABLE_moduleName___Formatter()
let interactor = ___VARIABLE_moduleName___Interactor()
let presenter = ___VARIABLE_moduleName___Presenter(view: moduleViewController, formatter: formatter, interactor: interactor, wireframe: self)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension ___VARIABLE_moduleName___Wireframe: ___VARIABLE_moduleName___WireframeInterface {
}
| 27.228571 | 149 | 0.756558 |
1eddecd5de8e8f6a0de374752a1faf70be37e7f9 | 3,790 | //
// TopicDetailCollectionViewFlowLayout.swift
// MakeTheBestOfThing
//
// Created by Qinting on 16/4/10.
// Copyright © 2016年 Qinting. All rights reserved.
//
//
import UIKit
class TopicDetailCollectionViewFlowLayout: UICollectionViewFlowLayout {
var topicInfoList: [TopicInfo]!
/// 一行显示的item个数
private let rowItemNum = 2
override func prepareLayout() {
super.prepareLayout()
let itemWidth = (kScreenWidth - (CGFloat(rowItemNum - 1) * minimumInteritemSpacing) - sectionInset.left - sectionInset.right) / CGFloat(rowItemNum)
// 计算所有item的布局属性
calcAllItemLayoutAttributeByItemWidth(itemWidth)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return layoutAttributes
}
/// 设置collectionView的滚动范围
override func collectionViewContentSize() -> CGSize {
let y = (colItemHeightValues?.sort().last)! - minimumInteritemSpacing;
return CGSizeMake(CGRectGetWidth(UIScreen.mainScreen().bounds), y + sectionInset.bottom)
}
// MARK: lazy loading
/// 布局属性数组
private lazy var layoutAttributes: [UICollectionViewLayoutAttributes]? = {
return [UICollectionViewLayoutAttributes]()
}()
/// 列高数组
private lazy var colItemHeightValues: [CGFloat]? = {
return [CGFloat](count: self.rowItemNum, repeatedValue: self.sectionInset.top)
}()
}
extension TopicDetailCollectionViewFlowLayout {
/**
计算所有item的布局属性
*/
private func calcAllItemLayoutAttributeByItemWidth(itemWidth: CGFloat) {
guard topicInfoList != nil else {
return
}
var index = 0
for _ in topicInfoList {
let attribute = calcItemLayoutAttribute(index++, itemWidth: itemWidth)
layoutAttributes?.append(attribute)
}
}
/**
计算一个item的布局属性
*/
private func calcItemLayoutAttribute(index: Int, itemWidth: CGFloat) -> UICollectionViewLayoutAttributes {
// 创建布局属性
let attribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: NSIndexPath(forItem: index, inSection: 0))
// 高度最小的列号和列高
let colAndHeight = findMinHeightColIndexAndHeight()
let x = sectionInset.left + CGFloat(colAndHeight.col) * (itemWidth + minimumInteritemSpacing)
let y = colAndHeight.height
let h = calcItemHeight(index, width: itemWidth)
// 将item的高度添加到数组进行记录
colItemHeightValues![colAndHeight.col] += (h + minimumLineSpacing)
// 设置frame
attribute.frame = CGRectMake(x, y, itemWidth, h)
return attribute
}
/**
根据数据源中的宽高计算等比例的高度
:returns: item的高度
*/
private func calcItemHeight(index: Int, width: CGFloat) -> CGFloat {
let bgImageH = width * 4.0 / 3.0
var descLabelH: CGFloat = 10 // 底部文字默认高度
if let desc = topicInfoList[index].content {
descLabelH = String.size(withText: desc, withFont: UIFont.fontWithSize(10), andMaxSize: CGSizeMake(width, CGFloat(MAXFLOAT))).height
}
let userIconH: CGFloat = 25 // 头像高度
let margin: CGFloat = 5
return margin + userIconH + margin + bgImageH + margin + descLabelH + margin
}
/**
找出高度最小的列
- returns: 列号和列高
*/
private func findMinHeightColIndexAndHeight() -> (col: Int, height: CGFloat) {
var minHeight: CGFloat = colItemHeightValues![0]
var index = 0
for i in 0..<rowItemNum {
let h = colItemHeightValues![i]
if minHeight > h {
minHeight = h
index = i
}
}
return (index, minHeight)
}
} | 31.322314 | 155 | 0.627704 |
205fbf78e9d9dc63444b97d83a5e4a2957785a5a | 329 | //
// Promise+Delay.swift
// DeLorean
//
// Created by sergio on 23/02/2018.
// Copyright © 2018 nc43tech. All rights reserved.
//
import Foundation
internal func delay(_ duration: TimeInterval, block: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: {
block()
})
}
| 20.5625 | 74 | 0.647416 |
e8597b501c0c011f373c8afd10875ecbadf7a54c | 2,759 | //
// DetailDataManager.swift
// ViperTaskManager
//
// Created by Aaron Lee on 19/11/16.
// Copyright © 2016 One Fat Giraffe. All rights reserved.
//
import Foundation
import RealmSwift
import Alamofire
import SwiftFetchedResultsController
protocol DetailDataManagerInputProtocol: class {
var interactor: DetailDataManagerOutputProtocol! { get set }
func updateTaskInPersistentStore(task: Task)
func updateTask(task: Task, callback: @escaping (_ result: Task?, _ error: Error?) -> ())
}
protocol DetailDataManagerOutputProtocol: class {
var dataManager: DetailDataManagerInputProtocol! { get set }
}
class DetailDataManager {
weak var interactor: DetailDataManagerOutputProtocol!
}
extension DetailDataManager: DetailDataManagerInputProtocol {
func updateTaskInPersistentStore(task: Task) {
let realm = try! Realm()
realm.beginWrite()
let predicate = NSPredicate(format: "taskId = %@", argumentArray: [task.taskId])
let taskEntity = realm.objects(TaskEntity.self).filter(predicate)[0]
taskEntity.title = task.title
taskEntity.completed = task.completed
taskEntity.deadline = task.deadline
realm.add(taskEntity, update: true)
try! realm.commitWrite()
}
func updateTask(task: Task, callback: @escaping (_ result: Task?, _ error: Error?) -> ()) {
let method = HTTPMethod.patch
let url = tasksServerEndpoint + "projects/" + task.projectId + "/tasks/" + task.taskId
let parameters: [String:AnyObject] = ["title": "\(task.title)" as AnyObject, "deadline": task.deadline.timeIntervalSince1970 as AnyObject, "completed": "\(task.completed)" as AnyObject]
Alamofire.SessionManager.default.request(url, method: method, parameters: parameters).responseJSON { (response) -> Void in
switch response.result {
case .success(let JSON):
let taskJson = JSON as! [String: AnyObject]
var deadlineInt: Int
if (taskJson["deadline"] is NSNull) {
deadlineInt = 0
} else {
deadlineInt = taskJson["deadline"] as! Int
}
let task = Task(taskId: taskJson["id"] as! String, projectId: taskJson["project_id"] as! String, title: taskJson["title"] as! String, deadline: Date(timeIntervalSince1970: TimeInterval(deadlineInt)), completed: taskJson["completed"] as! Bool)
print(task.completed)
callback(task, nil)
case .failure(let error):
print(error)
callback(nil, error)
}
}
}
}
| 36.786667 | 258 | 0.623414 |
ed52e17aeece54ca4ea582fa7f7e589a729fc23e | 75,607 | import Foundation
open class SwKeyStore {
public enum SecError: OSStatus, Error {
case unimplemented = -4
case param = -50
case allocate = -108
case notAvailable = -25291
case authFailed = -25293
case duplicateItem = -25299
case itemNotFound = -25300
case interactionNotAllowed = -25308
case decode = -26275
case missingEntitlement = -34018
public static var debugLevel = 1
init(_ status: OSStatus, function: String = #function, file: String = #file, line: Int = #line) {
self = SecError(rawValue: status)!
if SecError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
init(_ type: SecError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SecError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
}
public static func upsertKey(_ pemKey: String, keyTag: String,
options: [NSString : AnyObject] = [:]) throws {
let pemKeyAsData = pemKey.data(using: String.Encoding.utf8)!
var parameters: [NSString : AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrIsPermanent: true as AnyObject,
kSecAttrApplicationTag: keyTag as AnyObject,
kSecValueData: pemKeyAsData as AnyObject
]
options.forEach { k, v in
parameters[k] = v
}
var status = SecItemAdd(parameters as CFDictionary, nil)
if status == errSecDuplicateItem {
try delKey(keyTag)
status = SecItemAdd(parameters as CFDictionary, nil)
}
guard status == errSecSuccess else { throw SecError(status) }
}
public static func getKey(_ keyTag: String) throws -> String {
let parameters: [NSString : AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrApplicationTag : keyTag as AnyObject,
kSecReturnData : true as AnyObject
]
var data: AnyObject?
let status = SecItemCopyMatching(parameters as CFDictionary, &data)
guard status == errSecSuccess else { throw SecError(status) }
guard let pemKeyAsData = data as? Data else {
throw SecError(.decode)
}
guard let result = String(data: pemKeyAsData, encoding: String.Encoding.utf8) else {
throw SecError(.decode)
}
return result
}
public static func delKey(_ keyTag: String) throws {
let parameters: [NSString : AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: keyTag as AnyObject
]
let status = SecItemDelete(parameters as CFDictionary)
guard status == errSecSuccess else { throw SecError(status) }
}
}
open class SwKeyConvert {
public enum SwError: Error {
case invalidKey
case badPassphrase
case keyNotEncrypted
public static var debugLevel = 1
init(_ type: SwError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SwError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self)")
}
}
}
open class PrivateKey {
public static func pemToPKCS1DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PrivateKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
guard let pkcs1DERKey = PKCS8.PrivateKey.stripHeaderIfAny(derKey) else {
throw SwError(.invalidKey)
}
return pkcs1DERKey
}
public static func derToPKCS1PEM(_ derKey: Data) -> String {
return PEM.PrivateKey.toPEM(derKey)
}
public typealias EncMode = PEM.EncryptedPrivateKey.EncMode
public static func encryptPEM(_ pemKey: String, passphrase: String,
mode: EncMode) throws -> String {
do {
let derKey = try PEM.PrivateKey.toDER(pemKey)
return PEM.EncryptedPrivateKey.toPEM(derKey, passphrase: passphrase, mode: mode)
} catch {
throw SwError(.invalidKey)
}
}
public static func decryptPEM(_ pemKey: String, passphrase: String) throws -> String {
do {
let derKey = try PEM.EncryptedPrivateKey.toDER(pemKey, passphrase: passphrase)
return PEM.PrivateKey.toPEM(derKey)
} catch PEM.SwError.badPassphrase {
throw SwError(.badPassphrase)
} catch PEM.SwError.keyNotEncrypted {
throw SwError(.keyNotEncrypted)
} catch {
throw SwError(.invalidKey)
}
}
}
open class PublicKey {
public static func pemToPKCS1DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PublicKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
guard let pkcs1DERKey = PKCS8.PublicKey.stripHeaderIfAny(derKey) else {
throw SwError(.invalidKey)
}
return pkcs1DERKey
}
public static func pemToPKCS8DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PublicKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
return derKey
}
public static func derToPKCS1PEM(_ derKey: Data) -> String {
return PEM.PublicKey.toPEM(derKey)
}
public static func derToPKCS8PEM(_ derKey: Data) -> String {
let pkcs8Key = PKCS8.PublicKey.addHeader(derKey)
return PEM.PublicKey.toPEM(pkcs8Key)
}
}
}
open class PKCS8 {
open class PrivateKey {
// https://lapo.it/asn1js/
public static func getPKCS1DEROffset(_ derKey: Data) -> Int? {
let bytes = derKey.bytesView
var offset = 0
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x02 else { return nil }
offset += 3
// without PKCS8 header
guard bytes.length > offset else { return nil }
if bytes[offset] == 0x02 {
return 0
}
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
guard bytes.length > offset + OID.count else { return nil }
let slice = derKey.bytesViewRange(NSRange(location: offset, length: OID.count))
guard OID.elementsEqual(slice) else { return nil }
offset += OID.count
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x04 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
return offset
}
public static func stripHeaderIfAny(_ derKey: Data) -> Data? {
guard let offset = getPKCS1DEROffset(derKey) else {
return nil
}
return derKey.subdata(in: offset..<derKey.count)
}
public static func hasCorrectHeader(_ derKey: Data) -> Bool {
return getPKCS1DEROffset(derKey) != nil
}
}
open class PublicKey {
public static func addHeader(_ derKey: Data) -> Data {
var result = Data()
let encodingLength: Int = encodedOctets(derKey.count + 1).count
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
var builder: [UInt8] = []
// ASN.1 SEQUENCE
builder.append(0x30)
// Overall size, made of OID + bitstring encoding + actual key
let size = OID.count + 2 + encodingLength + derKey.count
let encodedSize = encodedOctets(size)
builder.append(contentsOf: encodedSize)
result.append(builder, count: builder.count)
result.append(OID, count: OID.count)
builder.removeAll(keepingCapacity: false)
builder.append(0x03)
builder.append(contentsOf: encodedOctets(derKey.count + 1))
builder.append(0x00)
result.append(builder, count: builder.count)
// Actual key bytes
result.append(derKey)
return result
}
// https://lapo.it/asn1js/
public static func getPKCS1DEROffset(_ derKey: Data) -> Int? {
let bytes = derKey.bytesView
var offset = 0
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
// without PKCS8 header
guard bytes.length > offset else { return nil }
if bytes[offset] == 0x02 {
return 0
}
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
guard bytes.length > offset + OID.count else { return nil }
let slice = derKey.bytesViewRange(NSRange(location: offset, length: OID.count))
guard OID.elementsEqual(slice) else { return nil }
offset += OID.count
// Type
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x03 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
// Contents should be separated by a null from the header
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x00 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
return offset
}
public static func stripHeaderIfAny(_ derKey: Data) -> Data? {
guard let offset = getPKCS1DEROffset(derKey) else {
return nil
}
return derKey.subdata(in: offset..<derKey.count)
}
public static func hasCorrectHeader(_ derKey: Data) -> Bool {
return getPKCS1DEROffset(derKey) != nil
}
fileprivate static func encodedOctets(_ int: Int) -> [UInt8] {
// Short form
if int < 128 {
return [UInt8(int)]
}
// Long form
let i = (int / 256) + 1
var len = int
var result: [UInt8] = [UInt8(i + 0x80)]
for _ in 0..<i {
result.insert(UInt8(len & 0xFF), at: 1)
len = len >> 8
}
return result
}
}
}
open class PEM {
public enum SwError: Error {
case parse(String)
case badPassphrase
case keyNotEncrypted
public static var debugLevel = 1
init(_ type: SwError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SwError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self)")
}
}
}
open class PrivateKey {
public static func toDER(_ pemKey: String) throws -> Data {
guard let strippedKey = stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let data = PEM.base64Decode(strippedKey) else {
throw SwError(.parse("base64decode"))
}
return data
}
public static func toPEM(_ derKey: Data) -> String {
let base64 = PEM.base64Encode(derKey)
return addRSAHeader(base64)
}
fileprivate static let prefix = "-----BEGIN PRIVATE KEY-----\n"
fileprivate static let suffix = "\n-----END PRIVATE KEY-----"
fileprivate static let rsaPrefix = "-----BEGIN RSA PRIVATE KEY-----\n"
fileprivate static let rsaSuffix = "\n-----END RSA PRIVATE KEY-----"
fileprivate static func addHeader(_ base64: String) -> String {
return prefix + base64 + suffix
}
fileprivate static func addRSAHeader(_ base64: String) -> String {
return rsaPrefix + base64 + rsaSuffix
}
fileprivate static func stripHeader(_ pemKey: String) -> String? {
return PEM.stripHeaderFooter(pemKey, header: prefix, footer: suffix) ??
PEM.stripHeaderFooter(pemKey, header: rsaPrefix, footer: rsaSuffix)
}
}
open class PublicKey {
public static func toDER(_ pemKey: String) throws -> Data {
guard let strippedKey = stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let data = PEM.base64Decode(strippedKey) else {
throw SwError(.parse("base64decode"))
}
return data
}
public static func toPEM(_ derKey: Data) -> String {
let base64 = PEM.base64Encode(derKey)
return addHeader(base64)
}
fileprivate static let pemPrefix = "-----BEGIN PUBLIC KEY-----\n"
fileprivate static let pemSuffix = "\n-----END PUBLIC KEY-----"
fileprivate static func addHeader(_ base64: String) -> String {
return pemPrefix + base64 + pemSuffix
}
fileprivate static func stripHeader(_ pemKey: String) -> String? {
return PEM.stripHeaderFooter(pemKey, header: pemPrefix, footer: pemSuffix)
}
}
// OpenSSL PKCS#1 compatible encrypted private key
open class EncryptedPrivateKey {
public enum EncMode {
case aes128CBC, aes256CBC
}
public static func toDER(_ pemKey: String, passphrase: String) throws -> Data {
guard let strippedKey = PrivateKey.stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let mode = getEncMode(strippedKey) else {
throw SwError(.keyNotEncrypted)
}
guard let iv = getIV(strippedKey) else {
throw SwError(.parse("iv"))
}
let aesKey = getAESKey(mode, passphrase: passphrase, iv: iv)
let base64Data = String(strippedKey[strippedKey.index(strippedKey.startIndex, offsetBy: aesHeaderLength)...])
guard let data = PEM.base64Decode(base64Data) else {
throw SwError(.parse("base64decode"))
}
guard let decrypted = try? decryptKey(data, key: aesKey, iv: iv) else {
throw SwError(.badPassphrase)
}
guard PKCS8.PrivateKey.hasCorrectHeader(decrypted) else {
throw SwError(.badPassphrase)
}
return decrypted
}
public static func toPEM(_ derKey: Data, passphrase: String, mode: EncMode) -> String {
let iv = CC.generateRandom(16)
let aesKey = getAESKey(mode, passphrase: passphrase, iv: iv)
let encrypted = encryptKey(derKey, key: aesKey, iv: iv)
let encryptedDERKey = addEncryptHeader(encrypted, iv: iv, mode: mode)
return PrivateKey.addRSAHeader(encryptedDERKey)
}
fileprivate static let aes128CBCInfo = "Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,"
fileprivate static let aes256CBCInfo = "Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,"
fileprivate static let aesInfoLength = aes128CBCInfo.count
fileprivate static let aesIVInHexLength = 32
fileprivate static let aesHeaderLength = aesInfoLength + aesIVInHexLength
fileprivate static func addEncryptHeader(_ key: Data, iv: Data, mode: EncMode) -> String {
return getHeader(mode) + iv.hexadecimalString() + "\n\n" + PEM.base64Encode(key)
}
fileprivate static func getHeader(_ mode: EncMode) -> String {
switch mode {
case .aes128CBC: return aes128CBCInfo
case .aes256CBC: return aes256CBCInfo
}
}
fileprivate static func getEncMode(_ strippedKey: String) -> EncMode? {
if strippedKey.hasPrefix(aes128CBCInfo) {
return .aes128CBC
}
if strippedKey.hasPrefix(aes256CBCInfo) {
return .aes256CBC
}
return nil
}
fileprivate static func getIV(_ strippedKey: String) -> Data? {
let ivInHex = String(strippedKey[strippedKey.index(strippedKey.startIndex, offsetBy: aesInfoLength) ..< strippedKey.index(strippedKey.startIndex, offsetBy: aesHeaderLength)])
return ivInHex.dataFromHexadecimalString()
}
fileprivate static func getAESKey(_ mode: EncMode, passphrase: String, iv: Data) -> Data {
switch mode {
case .aes128CBC: return getAES128Key(passphrase, iv: iv)
case .aes256CBC: return getAES256Key(passphrase, iv: iv)
}
}
fileprivate static func getAES128Key(_ passphrase: String, iv: Data) -> Data {
// 128bit_Key = MD5(Passphrase + Salt)
let pass = passphrase.data(using: String.Encoding.utf8)!
let salt = iv.subdata(in: 0..<8)
var key = pass
key.append(salt)
return CC.digest(key, alg: .md5)
}
fileprivate static func getAES256Key(_ passphrase: String, iv: Data) -> Data {
// 128bit_Key = MD5(Passphrase + Salt)
// 256bit_Key = 128bit_Key + MD5(128bit_Key + Passphrase + Salt)
let pass = passphrase.data(using: String.Encoding.utf8)!
let salt = iv.subdata(in: 0 ..< 8)
var first = pass
first.append(salt)
let aes128Key = CC.digest(first, alg: .md5)
var sec = aes128Key
sec.append(pass)
sec.append(salt)
var aes256Key = aes128Key
aes256Key.append(CC.digest(sec, alg: .md5))
return aes256Key
}
fileprivate static func encryptKey(_ data: Data, key: Data, iv: Data) -> Data {
return try! CC.crypt(
.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding,
data: data, key: key, iv: iv)
}
fileprivate static func decryptKey(_ data: Data, key: Data, iv: Data) throws -> Data {
return try CC.crypt(
.decrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding,
data: data, key: key, iv: iv)
}
}
fileprivate static func stripHeaderFooter(_ data: String, header: String, footer: String) -> String? {
guard data.hasPrefix(header) else {
return nil
}
guard let r = data.range(of: footer) else {
return nil
}
return String(data[header.endIndex ..< r.lowerBound])
}
fileprivate static func base64Decode(_ base64Data: String) -> Data? {
return Data(base64Encoded: base64Data, options: [.ignoreUnknownCharacters])
}
fileprivate static func base64Encode(_ key: Data) -> String {
return key.base64EncodedString(
options: [.lineLength64Characters, .endLineWithLineFeed])
}
}
open class CC {
public typealias CCCryptorStatus = Int32
public enum CCError: CCCryptorStatus, Error {
case paramError = -4300
case bufferTooSmall = -4301
case memoryFailure = -4302
case alignmentError = -4303
case decodeError = -4304
case unimplemented = -4305
case overflow = -4306
case rngFailure = -4307
case unspecifiedError = -4308
case callSequenceError = -4309
case keySizeError = -4310
case invalidKey = -4311
public static var debugLevel = 1
init(_ status: CCCryptorStatus, function: String = #function,
file: String = #file, line: Int = #line) {
self = CCError(rawValue: status)!
if CCError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
init(_ type: CCError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if CCError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
}
public static func generateRandom(_ size: Int) -> Data {
var data = Data(count: size)
data.withUnsafeMutableBytes { dataBytes -> Void in
_ = CCRandomGenerateBytes!(dataBytes.baseAddress!, size)
return
}
return data
}
public typealias CCDigestAlgorithm = UInt32
public enum DigestAlgorithm: CCDigestAlgorithm {
case none = 0
case md5 = 3
case rmd128 = 4, rmd160 = 5, rmd256 = 6, rmd320 = 7
case sha1 = 8
case sha224 = 9, sha256 = 10, sha384 = 11, sha512 = 12
var length: Int {
return CCDigestGetOutputSize!(self.rawValue)
}
}
public static func digest(_ data: Data, alg: DigestAlgorithm) -> Data {
var output = Data(count: alg.length)
withUnsafePointers(data, &output, { dataBytes, outputBytes in
_ = CCDigest!(alg.rawValue,
dataBytes,
data.count,
outputBytes)
})
return output
}
public typealias CCHmacAlgorithm = UInt32
public enum HMACAlg: CCHmacAlgorithm {
case sha1, md5, sha256, sha384, sha512, sha224
var digestLength: Int {
switch self {
case .sha1: return 20
case .md5: return 16
case .sha256: return 32
case .sha384: return 48
case .sha512: return 64
case .sha224: return 28
}
}
}
public static func HMAC(_ data: Data, alg: HMACAlg, key: Data) -> Data {
var buffer = Data(count: alg.digestLength)
withUnsafePointers(key, data, &buffer, { keyBytes, dataBytes, bufferBytes in
CCHmac!(alg.rawValue,
keyBytes, key.count,
dataBytes, data.count,
bufferBytes)
})
return buffer
}
public typealias CCOperation = UInt32
public enum OpMode: CCOperation {
case encrypt = 0, decrypt
}
public typealias CCMode = UInt32
public enum BlockMode: CCMode {
case ecb = 1, cbc, cfb, ctr, f8, lrw, ofb, xts, rc4, cfb8
var needIV: Bool {
switch self {
case .cbc, .cfb, .ctr, .ofb, .cfb8: return true
default: return false
}
}
}
public enum AuthBlockMode: CCMode {
case gcm = 11, ccm
}
public typealias CCAlgorithm = UInt32
public enum Algorithm: CCAlgorithm {
case aes = 0, des, threeDES, cast, rc4, rc2, blowfish
var blockSize: Int? {
switch self {
case .aes: return 16
case .des: return 8
case .threeDES: return 8
case .cast: return 8
case .rc2: return 8
case .blowfish: return 8
default: return nil
}
}
}
public typealias CCPadding = UInt32
public enum Padding: CCPadding {
case noPadding = 0, pkcs7Padding
}
public static func crypt(_ opMode: OpMode, blockMode: BlockMode,
algorithm: Algorithm, padding: Padding,
data: Data, key: Data, iv: Data) throws -> Data {
if blockMode.needIV {
guard iv.count == algorithm.blockSize else { throw CCError(.paramError) }
}
var cryptor: CCCryptorRef? = nil
var status = withUnsafePointers(iv, key, { ivBytes, keyBytes in
return CCCryptorCreateWithMode!(
opMode.rawValue, blockMode.rawValue,
algorithm.rawValue, padding.rawValue,
ivBytes, keyBytes, key.count,
nil, 0, 0,
CCModeOptions(), &cryptor)
})
guard status == noErr else { throw CCError(status) }
defer { _ = CCCryptorRelease!(cryptor!) }
let needed = CCCryptorGetOutputLength!(cryptor!, data.count, true)
var result = Data(count: needed)
let rescount = result.count
var updateLen: size_t = 0
status = withUnsafePointers(data, &result, { dataBytes, resultBytes in
return CCCryptorUpdate!(
cryptor!,
dataBytes, data.count,
resultBytes, rescount,
&updateLen)
})
guard status == noErr else { throw CCError(status) }
var finalLen: size_t = 0
status = result.withUnsafeMutableBytes { resultBytes -> OSStatus in
return CCCryptorFinal!(
cryptor!,
resultBytes.baseAddress! + updateLen,
rescount - updateLen,
&finalLen)
}
guard status == noErr else { throw CCError(status) }
result.count = updateLen + finalLen
return result
}
// The same behaviour as in the CCM pdf
// http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
public static func cryptAuth(_ opMode: OpMode, blockMode: AuthBlockMode, algorithm: Algorithm,
data: Data, aData: Data,
key: Data, iv: Data, tagLength: Int) throws -> Data {
let cryptFun = blockMode == .gcm ? GCM.crypt : CCM.crypt
if opMode == .encrypt {
let (cipher, tag) = try cryptFun(opMode, algorithm, data,
key, iv, aData, tagLength)
var result = cipher
result.append(tag)
return result
} else {
let cipher = data.subdata(in: 0..<(data.count - tagLength))
let tag = data.subdata(
in: (data.count - tagLength)..<data.count)
let (plain, vTag) = try cryptFun(opMode, algorithm, cipher,
key, iv, aData, tagLength)
guard tag == vTag else {
throw CCError(.decodeError)
}
return plain
}
}
public static func digestAvailable() -> Bool {
return CCDigest != nil &&
CCDigestGetOutputSize != nil
}
public static func randomAvailable() -> Bool {
return CCRandomGenerateBytes != nil
}
public static func hmacAvailable() -> Bool {
return CCHmac != nil
}
public static func cryptorAvailable() -> Bool {
return CCCryptorCreateWithMode != nil &&
CCCryptorGetOutputLength != nil &&
CCCryptorUpdate != nil &&
CCCryptorFinal != nil &&
CCCryptorRelease != nil
}
public static func available() -> Bool {
return digestAvailable() &&
randomAvailable() &&
hmacAvailable() &&
cryptorAvailable() &&
KeyDerivation.available() &&
KeyWrap.available() &&
RSA.available() &&
DH.available() &&
EC.available() &&
CRC.available() &&
CMAC.available() &&
GCM.available() &&
CCM.available()
}
fileprivate typealias CCCryptorRef = UnsafeRawPointer
fileprivate typealias CCRNGStatus = CCCryptorStatus
fileprivate typealias CC_LONG = UInt32
fileprivate typealias CCModeOptions = UInt32
fileprivate typealias CCRandomGenerateBytesT = @convention(c) (
_ bytes: UnsafeMutableRawPointer,
_ count: size_t) -> CCRNGStatus
fileprivate typealias CCDigestGetOutputSizeT = @convention(c) (
_ algorithm: CCDigestAlgorithm) -> size_t
fileprivate typealias CCDigestT = @convention(c) (
_ algorithm: CCDigestAlgorithm,
_ data: UnsafeRawPointer,
_ dataLen: size_t,
_ output: UnsafeMutableRawPointer) -> CInt
fileprivate typealias CCHmacT = @convention(c) (
_ algorithm: CCHmacAlgorithm,
_ key: UnsafeRawPointer,
_ keyLength: Int,
_ data: UnsafeRawPointer,
_ dataLength: Int,
_ macOut: UnsafeMutableRawPointer) -> Void
fileprivate typealias CCCryptorCreateWithModeT = @convention(c)(
_ op: CCOperation,
_ mode: CCMode,
_ alg: CCAlgorithm,
_ padding: CCPadding,
_ iv: UnsafeRawPointer?,
_ key: UnsafeRawPointer, _ keyLength: Int,
_ tweak: UnsafeRawPointer?, _ tweakLength: Int,
_ numRounds: Int32, _ options: CCModeOptions,
_ cryptorRef: UnsafeMutablePointer<CCCryptorRef?>) -> CCCryptorStatus
fileprivate typealias CCCryptorGetOutputLengthT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ inputLength: size_t,
_ final: Bool) -> size_t
fileprivate typealias CCCryptorUpdateT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ dataIn: UnsafeRawPointer,
_ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate typealias CCCryptorFinalT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ dataOut: UnsafeMutableRawPointer,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate typealias CCCryptorReleaseT = @convention(c)
(_ cryptorRef: CCCryptorRef) -> CCCryptorStatus
fileprivate static let dl = dlopen("/usr/lib/system/libcommonCrypto.dylib", RTLD_NOW)
fileprivate static let CCRandomGenerateBytes: CCRandomGenerateBytesT? =
getFunc(dl!, f: "CCRandomGenerateBytes")
fileprivate static let CCDigestGetOutputSize: CCDigestGetOutputSizeT? =
getFunc(dl!, f: "CCDigestGetOutputSize")
fileprivate static let CCDigest: CCDigestT? = getFunc(dl!, f: "CCDigest")
fileprivate static let CCHmac: CCHmacT? = getFunc(dl!, f: "CCHmac")
fileprivate static let CCCryptorCreateWithMode: CCCryptorCreateWithModeT? =
getFunc(dl!, f: "CCCryptorCreateWithMode")
fileprivate static let CCCryptorGetOutputLength: CCCryptorGetOutputLengthT? =
getFunc(dl!, f: "CCCryptorGetOutputLength")
fileprivate static let CCCryptorUpdate: CCCryptorUpdateT? =
getFunc(dl!, f: "CCCryptorUpdate")
fileprivate static let CCCryptorFinal: CCCryptorFinalT? =
getFunc(dl!, f: "CCCryptorFinal")
fileprivate static let CCCryptorRelease: CCCryptorReleaseT? =
getFunc(dl!, f: "CCCryptorRelease")
open class GCM {
public static func crypt(_ opMode: OpMode, algorithm: Algorithm, data: Data,
key: Data, iv: Data,
aData: Data, tagLength: Int) throws -> (Data, Data) {
var result = Data(count: data.count)
var tagLength_ = tagLength
var tag = Data(count: tagLength)
let status = withUnsafePointers(key, iv, aData, data, &result, &tag, {
keyBytes, ivBytes, aDataBytes, dataBytes, resultBytes, tagBytes in
return CCCryptorGCM!(opMode.rawValue, algorithm.rawValue,
keyBytes, key.count, ivBytes, iv.count,
aDataBytes, aData.count,
dataBytes, data.count,
resultBytes, tagBytes, &tagLength_)
})
guard status == noErr else { throw CCError(status) }
tag.count = tagLength_
return (result, tag)
}
public static func available() -> Bool {
if CCCryptorGCM != nil {
return true
}
return false
}
fileprivate typealias CCCryptorGCMT = @convention(c) (_ op: CCOperation, _ alg: CCAlgorithm,
_ key: UnsafeRawPointer, _ keyLength: Int,
_ iv: UnsafeRawPointer, _ ivLen: Int,
_ aData: UnsafeRawPointer, _ aDataLen: Int,
_ dataIn: UnsafeRawPointer, _ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer,
_ tag: UnsafeRawPointer, _ tagLength: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate static let CCCryptorGCM: CCCryptorGCMT? = getFunc(dl!, f: "CCCryptorGCM")
}
open class CCM {
public static func crypt(_ opMode: OpMode, algorithm: Algorithm, data: Data,
key: Data, iv: Data,
aData: Data, tagLength: Int) throws -> (Data, Data) {
var cryptor: CCCryptorRef? = nil
var status = key.withUnsafeBytes { keyBytes -> OSStatus in
CCCryptorCreateWithMode!(
opMode.rawValue, AuthBlockMode.ccm.rawValue,
algorithm.rawValue, Padding.noPadding.rawValue,
nil, keyBytes.baseAddress!, key.count, nil, 0,
0, CCModeOptions(), &cryptor)
}
guard status == noErr else { throw CCError(status) }
defer { _ = CCCryptorRelease!(cryptor!) }
status = CCCryptorAddParameter!(cryptor!,
Parameter.dataSize.rawValue, nil, data.count)
guard status == noErr else { throw CCError(status) }
status = CCCryptorAddParameter!(cryptor!, Parameter.macSize.rawValue, nil, tagLength)
guard status == noErr else { throw CCError(status) }
status = iv.withUnsafeBytes { ivBytes -> OSStatus in
CCCryptorAddParameter!(cryptor!, Parameter.iv.rawValue, ivBytes.baseAddress!, iv.count)
}
guard status == noErr else { throw CCError(status) }
status = aData.withUnsafeBytes { aDataBytes -> OSStatus in
CCCryptorAddParameter!(cryptor!, Parameter.authData.rawValue, aDataBytes.baseAddress!, aData.count)
}
guard status == noErr else { throw CCError(status) }
var result = Data(count: data.count)
let rescount = result.count
var updateLen: size_t = 0
status = withUnsafePointers(data, &result, { dataBytes, resultBytes in
return CCCryptorUpdate!(
cryptor!, dataBytes, data.count,
resultBytes, rescount,
&updateLen)
})
guard status == noErr else { throw CCError(status) }
var finalLen: size_t = 0
status = result.withUnsafeMutableBytes { resultBytes -> OSStatus in
CCCryptorFinal!(cryptor!, resultBytes.baseAddress! + updateLen,
rescount - updateLen,
&finalLen)
}
guard status == noErr else { throw CCError(status) }
result.count = updateLen + finalLen
var tagLength_ = tagLength
var tag = Data(count: tagLength)
status = tag.withUnsafeMutableBytes { tagBytes -> OSStatus in
CCCryptorGetParameter!(cryptor!, Parameter.authTag.rawValue,
tagBytes.baseAddress!, &tagLength_)
}
guard status == noErr else { throw CCError(status) }
tag.count = tagLength_
return (result, tag)
}
public static func available() -> Bool {
if CCCryptorAddParameter != nil &&
CCCryptorGetParameter != nil {
return true
}
return false
}
fileprivate typealias CCParameter = UInt32
fileprivate enum Parameter: CCParameter {
case iv, authData, macSize, dataSize, authTag
}
fileprivate typealias CCCryptorAddParameterT = @convention(c) (_ cryptorRef: CCCryptorRef,
_ parameter: CCParameter,
_ data: UnsafeRawPointer?, _ dataLength: size_t) -> CCCryptorStatus
fileprivate static let CCCryptorAddParameter: CCCryptorAddParameterT? =
getFunc(dl!, f: "CCCryptorAddParameter")
fileprivate typealias CCCryptorGetParameterT = @convention(c) (_ cryptorRef: CCCryptorRef,
_ parameter: CCParameter,
_ data: UnsafeRawPointer, _ dataLength: UnsafeMutablePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCCryptorGetParameter: CCCryptorGetParameterT? =
getFunc(dl!, f: "CCCryptorGetParameter")
}
open class RSA {
public typealias CCAsymmetricPadding = UInt32
public enum AsymmetricPadding: CCAsymmetricPadding {
case pkcs1 = 1001
case oaep = 1002
}
public enum AsymmetricSAPadding: UInt32 {
case pkcs15 = 1001
case pss = 1002
}
public static func generateKeyPair(_ keySize: Int = 4096) throws -> (Data, Data) {
var privateKey: CCRSACryptorRef? = nil
var publicKey: CCRSACryptorRef? = nil
let status = CCRSACryptorGeneratePair!(
keySize,
65537,
&publicKey,
&privateKey)
guard status == noErr else { throw CCError(status) }
defer {
CCRSACryptorRelease!(privateKey!)
CCRSACryptorRelease!(publicKey!)
}
let privDERKey = try exportToDERKey(privateKey!)
let pubDERKey = try exportToDERKey(publicKey!)
return (privDERKey, pubDERKey)
}
public static func getPublicKeyFromPrivateKey(_ derKey: Data) throws -> Data {
let key = try importFromDERKey(derKey)
defer { CCRSACryptorRelease!(key) }
guard getKeyType(key) == .privateKey else { throw CCError(.paramError) }
let publicKey = CCRSACryptorGetPublicKeyFromPrivateKey!(key)
defer { CCRSACryptorRelease!(publicKey) }
let pubDERKey = try exportToDERKey(publicKey)
return pubDERKey
}
public static func encrypt(_ data: Data, derKey: Data, tag: Data,
padding: AsymmetricPadding,
digest: DigestAlgorithm) throws -> Data {
let key = try importFromDERKey(derKey)
defer { CCRSACryptorRelease!(key) }
var bufferSize = getKeySize(key)
var buffer = Data(count: bufferSize)
let status = withUnsafePointers(data, tag, &buffer, {
dataBytes, tagBytes, bufferBytes in
return CCRSACryptorEncrypt!(
key,
padding.rawValue,
dataBytes, data.count,
bufferBytes, &bufferSize,
tagBytes, tag.count,
digest.rawValue)
})
guard status == noErr else { throw CCError(status) }
buffer.count = bufferSize
return buffer
}
public static func decrypt(_ data: Data, derKey: Data, tag: Data,
padding: AsymmetricPadding,
digest: DigestAlgorithm) throws -> (Data, Int) {
let key = try importFromDERKey(derKey)
defer { CCRSACryptorRelease!(key) }
let blockSize = getKeySize(key)
var bufferSize = blockSize
var buffer = Data(count: bufferSize)
let status = withUnsafePointers(data, tag, &buffer, {
dataBytes, tagBytes, bufferBytes in
return CCRSACryptorDecrypt!(
key,
padding.rawValue,
dataBytes, data.count,
bufferBytes, &bufferSize,
tagBytes, tag.count,
digest.rawValue)
})
guard status == noErr else { throw CCError(status) }
buffer.count = bufferSize
return (buffer, blockSize)
}
fileprivate static func importFromDERKey(_ derKey: Data) throws -> CCRSACryptorRef {
var key: CCRSACryptorRef? = nil
let status = derKey.withUnsafeBytes { derKeyBytes -> OSStatus in
CCRSACryptorImport!(
derKeyBytes.baseAddress!,
derKey.count,
&key)
}
guard status == noErr else { throw CCError(status) }
return key!
}
fileprivate static func exportToDERKey(_ key: CCRSACryptorRef) throws -> Data {
var derKeyLength = 8192
var derKey = Data(count: derKeyLength)
let status = derKey.withUnsafeMutableBytes { derKeyBytes -> OSStatus in
CCRSACryptorExport!(key, derKeyBytes.baseAddress!, &derKeyLength)
}
guard status == noErr else { throw CCError(status) }
derKey.count = derKeyLength
return derKey
}
fileprivate static func getKeyType(_ key: CCRSACryptorRef) -> KeyType {
return KeyType(rawValue: CCRSAGetKeyType!(key))!
}
fileprivate static func getKeySize(_ key: CCRSACryptorRef) -> Int {
return Int(CCRSAGetKeySize!(key)/8)
}
public static func sign(_ message: Data, derKey: Data, padding: AsymmetricSAPadding,
digest: DigestAlgorithm, saltLen: Int) throws -> Data {
let key = try importFromDERKey(derKey)
defer { CCRSACryptorRelease!(key) }
guard getKeyType(key) == .privateKey else { throw CCError(.paramError) }
let keySize = getKeySize(key)
switch padding {
case .pkcs15:
let hash = CC.digest(message, alg: digest)
var signedDataLength = keySize
var signedData = Data(count:signedDataLength)
let status = withUnsafePointers(hash, &signedData, {
hashBytes, signedDataBytes in
return CCRSACryptorSign!(
key,
AsymmetricPadding.pkcs1.rawValue,
hashBytes, hash.count,
digest.rawValue, 0 /*unused*/,
signedDataBytes, &signedDataLength)
})
guard status == noErr else { throw CCError(status) }
signedData.count = signedDataLength
return signedData
case .pss:
let encMessage = try add_pss_padding(
digest,
saltLength: saltLen,
keyLength: keySize,
message: message)
return try crypt(encMessage, key: key)
}
}
public static func verify(_ message: Data, derKey: Data, padding: AsymmetricSAPadding,
digest: DigestAlgorithm, saltLen: Int,
signedData: Data) throws -> Bool {
let key = try importFromDERKey(derKey)
defer { CCRSACryptorRelease!(key) }
guard getKeyType(key) == .publicKey else { throw CCError(.paramError) }
let keySize = getKeySize(key)
switch padding {
case .pkcs15:
let hash = CC.digest(message, alg: digest)
let status = withUnsafePointers(hash, signedData, {
hashBytes, signedDataBytes in
return CCRSACryptorVerify!(
key,
padding.rawValue,
hashBytes, hash.count,
digest.rawValue, 0 /*unused*/,
signedDataBytes, signedData.count)
})
let kCCNotVerified: CCCryptorStatus = -4306
if status == kCCNotVerified {
return false
}
guard status == noErr else { throw CCError(status) }
return true
case .pss:
let encoded = try crypt(signedData, key:key)
return try verify_pss_padding(
digest,
saltLength: saltLen,
keyLength: keySize,
message: message,
encMessage: encoded)
}
}
fileprivate static func crypt(_ data: Data, key: CCRSACryptorRef) throws -> Data {
var outLength = data.count
var out = Data(count: outLength)
let status = withUnsafePointers(data, &out, { dataBytes, outBytes in
return CCRSACryptorCrypt!(
key,
dataBytes, data.count,
outBytes, &outLength)
})
guard status == noErr else { throw CCError(status) }
out.count = outLength
return out
}
fileprivate static func mgf1(_ digest: DigestAlgorithm,
seed: Data, maskLength: Int) -> Data {
var tseed = seed
tseed.append(contentsOf: [0,0,0,0] as [UInt8])
var interval = maskLength / digest.length
if maskLength % digest.length != 0 {
interval += 1
}
func pack(_ n: Int) -> [UInt8] {
return [
UInt8(n>>24 & 0xff),
UInt8(n>>16 & 0xff),
UInt8(n>>8 & 0xff),
UInt8(n>>0 & 0xff)
]
}
var mask = Data()
for counter in 0 ..< interval {
tseed.replaceSubrange((tseed.count - 4) ..< tseed.count, with: pack(counter))
mask.append(CC.digest(tseed, alg: digest))
}
mask.count = maskLength
return mask
}
fileprivate static func xorData(_ data1: Data, _ data2: Data) -> Data {
precondition(data1.count == data2.count)
var ret = Data(count: data1.count)
let retcount = ret.count
withUnsafePointers(data1, data2, &ret, {(
b1: UnsafePointer<UInt8>,
b2: UnsafePointer<UInt8>,
r: UnsafeMutablePointer<UInt8>) in
for i in 0 ..< retcount {
r[i] = b1[i] ^ b2[i]
}
})
return ret
}
fileprivate static func add_pss_padding(_ digest: DigestAlgorithm,
saltLength: Int,
keyLength: Int,
message: Data) throws -> Data {
if keyLength < 16 || saltLength < 0 {
throw CCError(.paramError)
}
// The maximal bit size of a non-negative integer is one less than the bit
// size of the key since the first bit is used to store sign
let emBits = keyLength * 8 - 1
var emLength = emBits / 8
if emBits % 8 != 0 {
emLength += 1
}
let hash = CC.digest(message, alg: digest)
if emLength < hash.count + saltLength + 2 {
throw CCError(.paramError)
}
let salt = CC.generateRandom(saltLength)
var mPrime = Data(count: 8)
mPrime.append(hash)
mPrime.append(salt)
let mPrimeHash = CC.digest(mPrime, alg: digest)
let padding = Data(count: emLength - saltLength - hash.count - 2)
var db = padding
db.append([0x01] as [UInt8], count: 1)
db.append(salt)
let dbMask = mgf1(digest, seed: mPrimeHash, maskLength: emLength - hash.count - 1)
var maskedDB = xorData(db, dbMask)
let zeroBits = 8 * emLength - emBits
maskedDB.withUnsafeMutableBytes { maskedDBBytes -> Void in
maskedDBBytes.bindMemory(to: UInt8.self).baseAddress![0] &= 0xff >> UInt8(zeroBits)
}
var ret = maskedDB
ret.append(mPrimeHash)
ret.append([0xBC] as [UInt8], count: 1)
return ret
}
fileprivate static func verify_pss_padding(_ digest: DigestAlgorithm,
saltLength: Int, keyLength: Int,
message: Data,
encMessage: Data) throws -> Bool {
if keyLength < 16 || saltLength < 0 {
throw CCError(.paramError)
}
guard encMessage.count > 0 else {
return false
}
let emBits = keyLength * 8 - 1
var emLength = emBits / 8
if emBits % 8 != 0 {
emLength += 1
}
let hash = CC.digest(message, alg: digest)
if emLength < hash.count + saltLength + 2 {
return false
}
if encMessage.bytesView[encMessage.count-1] != 0xBC {
return false
}
let zeroBits = 8 * emLength - emBits
let zeroBitsM = 8 - zeroBits
let maskedDBLength = emLength - hash.count - 1
let maskedDB = encMessage.subdata(in: 0..<maskedDBLength)
if Int(maskedDB.bytesView[0]) >> zeroBitsM != 0 {
return false
}
let mPrimeHash = encMessage.subdata(in: maskedDBLength ..< maskedDBLength + hash.count)
let dbMask = mgf1(digest, seed: mPrimeHash, maskLength: emLength - hash.count - 1)
var db = xorData(maskedDB, dbMask)
db.withUnsafeMutableBytes { dbBytes -> Void in
dbBytes.bindMemory(to: UInt8.self).baseAddress![0] &= 0xff >> UInt8(zeroBits)
}
let zeroLength = emLength - hash.count - saltLength - 2
let zeroString = Data(count:zeroLength)
if db.subdata(in: 0 ..< zeroLength) != zeroString {
return false
}
if db.bytesView[zeroLength] != 0x01 {
return false
}
let salt = db.subdata(in: (db.count - saltLength) ..< db.count)
var mPrime = Data(count:8)
mPrime.append(hash)
mPrime.append(salt)
let mPrimeHash2 = CC.digest(mPrime, alg: digest)
if mPrimeHash != mPrimeHash2 {
return false
}
return true
}
public static func available() -> Bool {
return CCRSACryptorGeneratePair != nil &&
CCRSACryptorGetPublicKeyFromPrivateKey != nil &&
CCRSACryptorRelease != nil &&
CCRSAGetKeyType != nil &&
CCRSAGetKeySize != nil &&
CCRSACryptorEncrypt != nil &&
CCRSACryptorDecrypt != nil &&
CCRSACryptorExport != nil &&
CCRSACryptorImport != nil &&
CCRSACryptorSign != nil &&
CCRSACryptorVerify != nil &&
CCRSACryptorCrypt != nil
}
fileprivate typealias CCRSACryptorRef = UnsafeRawPointer
fileprivate typealias CCRSAKeyType = UInt32
fileprivate enum KeyType: CCRSAKeyType {
case publicKey = 0, privateKey
case blankPublicKey = 97, blankPrivateKey
case badKey = 99
}
fileprivate typealias CCRSACryptorGeneratePairT = @convention(c) (
_ keySize: Int,
_ e: UInt32,
_ publicKey: UnsafeMutablePointer<CCRSACryptorRef?>,
_ privateKey: UnsafeMutablePointer<CCRSACryptorRef?>) -> CCCryptorStatus
fileprivate static let CCRSACryptorGeneratePair: CCRSACryptorGeneratePairT? =
getFunc(CC.dl!, f: "CCRSACryptorGeneratePair")
fileprivate typealias CCRSACryptorGetPublicKeyFromPrivateKeyT = @convention(c) (CCRSACryptorRef) -> CCRSACryptorRef
fileprivate static let CCRSACryptorGetPublicKeyFromPrivateKey: CCRSACryptorGetPublicKeyFromPrivateKeyT? =
getFunc(CC.dl!, f: "CCRSACryptorGetPublicKeyFromPrivateKey")
fileprivate typealias CCRSACryptorReleaseT = @convention(c) (CCRSACryptorRef) -> Void
fileprivate static let CCRSACryptorRelease: CCRSACryptorReleaseT? =
getFunc(dl!, f: "CCRSACryptorRelease")
fileprivate typealias CCRSAGetKeyTypeT = @convention(c) (CCRSACryptorRef) -> CCRSAKeyType
fileprivate static let CCRSAGetKeyType: CCRSAGetKeyTypeT? = getFunc(dl!, f: "CCRSAGetKeyType")
fileprivate typealias CCRSAGetKeySizeT = @convention(c) (CCRSACryptorRef) -> Int32
fileprivate static let CCRSAGetKeySize: CCRSAGetKeySizeT? = getFunc(dl!, f: "CCRSAGetKeySize")
fileprivate typealias CCRSACryptorEncryptT = @convention(c) (
_ publicKey: CCRSACryptorRef,
_ padding: CCAsymmetricPadding,
_ plainText: UnsafeRawPointer,
_ plainTextLen: Int,
_ cipherText: UnsafeMutableRawPointer,
_ cipherTextLen: UnsafeMutablePointer<Int>,
_ tagData: UnsafeRawPointer,
_ tagDataLen: Int,
_ digestType: CCDigestAlgorithm) -> CCCryptorStatus
fileprivate static let CCRSACryptorEncrypt: CCRSACryptorEncryptT? =
getFunc(dl!, f: "CCRSACryptorEncrypt")
fileprivate typealias CCRSACryptorDecryptT = @convention (c) (
_ privateKey: CCRSACryptorRef,
_ padding: CCAsymmetricPadding,
_ cipherText: UnsafeRawPointer,
_ cipherTextLen: Int,
_ plainText: UnsafeMutableRawPointer,
_ plainTextLen: UnsafeMutablePointer<Int>,
_ tagData: UnsafeRawPointer,
_ tagDataLen: Int,
_ digestType: CCDigestAlgorithm) -> CCCryptorStatus
fileprivate static let CCRSACryptorDecrypt: CCRSACryptorDecryptT? =
getFunc(dl!, f: "CCRSACryptorDecrypt")
fileprivate typealias CCRSACryptorExportT = @convention(c) (
_ key: CCRSACryptorRef,
_ out: UnsafeMutableRawPointer,
_ outLen: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate static let CCRSACryptorExport: CCRSACryptorExportT? =
getFunc(dl!, f: "CCRSACryptorExport")
fileprivate typealias CCRSACryptorImportT = @convention(c) (
_ keyPackage: UnsafeRawPointer,
_ keyPackageLen: Int,
_ key: UnsafeMutablePointer<CCRSACryptorRef?>) -> CCCryptorStatus
fileprivate static let CCRSACryptorImport: CCRSACryptorImportT? =
getFunc(dl!, f: "CCRSACryptorImport")
fileprivate typealias CCRSACryptorSignT = @convention(c) (
_ privateKey: CCRSACryptorRef,
_ padding: CCAsymmetricPadding,
_ hashToSign: UnsafeRawPointer,
_ hashSignLen: size_t,
_ digestType: CCDigestAlgorithm,
_ saltLen: size_t,
_ signedData: UnsafeMutableRawPointer,
_ signedDataLen: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate static let CCRSACryptorSign: CCRSACryptorSignT? =
getFunc(dl!, f: "CCRSACryptorSign")
fileprivate typealias CCRSACryptorVerifyT = @convention(c) (
_ publicKey: CCRSACryptorRef,
_ padding: CCAsymmetricPadding,
_ hash: UnsafeRawPointer,
_ hashLen: size_t,
_ digestType: CCDigestAlgorithm,
_ saltLen: size_t,
_ signedData: UnsafeRawPointer,
_ signedDataLen: size_t) -> CCCryptorStatus
fileprivate static let CCRSACryptorVerify: CCRSACryptorVerifyT? =
getFunc(dl!, f: "CCRSACryptorVerify")
fileprivate typealias CCRSACryptorCryptT = @convention(c) (
_ rsaKey: CCRSACryptorRef,
_ data: UnsafeRawPointer, _ dataLength: size_t,
_ out: UnsafeMutableRawPointer,
_ outLength: UnsafeMutablePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCRSACryptorCrypt: CCRSACryptorCryptT? =
getFunc(dl!, f: "CCRSACryptorCrypt")
}
open class DH {
public enum DHParam {
case rfc3526Group5
case rfc2409Group2
}
// this is stateful in CommonCrypto too, sry
open class DH {
fileprivate var ref: CCDHRef? = nil
public init(dhParam: DHParam) throws {
if dhParam == .rfc3526Group5 {
ref = CCDHCreate!(kCCDHRFC3526Group5!)
} else {
ref = CCDHCreate!(kCCDHRFC2409Group2!)
}
guard ref != nil else {
throw CCError(.paramError)
}
}
open func generateKey() throws -> Data {
var outputLength = 8192
var output = Data(count: outputLength)
let status = output.withUnsafeMutableBytes { outputBytes -> OSStatus in
CCDHGenerateKey!(ref!, outputBytes.baseAddress!, &outputLength)
}
output.count = outputLength
guard status != -1 else {
throw CCError(.paramError)
}
return output
}
open func computeKey(_ peerKey: Data) throws -> Data {
var sharedKeyLength = 8192
var sharedKey = Data(count: sharedKeyLength)
let status = withUnsafePointers(peerKey, &sharedKey, {
peerKeyBytes, sharedKeyBytes in
return CCDHComputeKey!(
sharedKeyBytes, &sharedKeyLength,
peerKeyBytes, peerKey.count,
ref!)
})
sharedKey.count = sharedKeyLength
guard status == 0 else {
throw CCError(.paramError)
}
return sharedKey
}
deinit {
if ref != nil {
CCDHRelease!(ref!)
}
}
}
public static func available() -> Bool {
return CCDHCreate != nil &&
CCDHRelease != nil &&
CCDHGenerateKey != nil &&
CCDHComputeKey != nil &&
CCDHParametersCreateFromData != nil &&
CCDHParametersRelease != nil
}
fileprivate typealias CCDHParameters = UnsafeRawPointer
fileprivate typealias CCDHRef = UnsafeRawPointer
fileprivate typealias kCCDHRFC3526Group5TM = UnsafePointer<CCDHParameters>
fileprivate static let kCCDHRFC3526Group5M: kCCDHRFC3526Group5TM? =
getFunc(dl!, f: "kCCDHRFC3526Group5")
fileprivate static let kCCDHRFC3526Group5 = kCCDHRFC3526Group5M?.pointee
fileprivate typealias kCCDHRFC2409Group2TM = UnsafePointer<CCDHParameters>
fileprivate static let kCCDHRFC2409Group2M: kCCDHRFC2409Group2TM? =
getFunc(dl!, f: "kCCDHRFC2409Group2")
fileprivate static let kCCDHRFC2409Group2 = kCCDHRFC2409Group2M?.pointee
fileprivate typealias CCDHCreateT = @convention(c) (
_ dhParameter: CCDHParameters) -> CCDHRef
fileprivate static let CCDHCreate: CCDHCreateT? = getFunc(dl!, f: "CCDHCreate")
fileprivate typealias CCDHReleaseT = @convention(c) (
_ ref: CCDHRef) -> Void
fileprivate static let CCDHRelease: CCDHReleaseT? = getFunc(dl!, f: "CCDHRelease")
fileprivate typealias CCDHGenerateKeyT = @convention(c) (
_ ref: CCDHRef,
_ output: UnsafeMutableRawPointer, _ outputLength: UnsafeMutablePointer<size_t>) -> CInt
fileprivate static let CCDHGenerateKey: CCDHGenerateKeyT? = getFunc(dl!, f: "CCDHGenerateKey")
fileprivate typealias CCDHComputeKeyT = @convention(c) (
_ sharedKey: UnsafeMutableRawPointer, _ sharedKeyLen: UnsafeMutablePointer<size_t>,
_ peerPubKey: UnsafeRawPointer, _ peerPubKeyLen: size_t,
_ ref: CCDHRef) -> CInt
fileprivate static let CCDHComputeKey: CCDHComputeKeyT? = getFunc(dl!, f: "CCDHComputeKey")
fileprivate typealias CCDHParametersCreateFromDataT = @convention(c) (
_ p: UnsafeRawPointer, _ pLen: Int,
_ g: UnsafeRawPointer, _ gLen: Int,
_ l: Int) -> CCDHParameters
fileprivate static let CCDHParametersCreateFromData: CCDHParametersCreateFromDataT? = getFunc(dl!, f: "CCDHParametersCreateFromData")
fileprivate typealias CCDHParametersReleaseT = @convention(c) (
_ parameters: CCDHParameters) -> Void
fileprivate static let CCDHParametersRelease: CCDHParametersReleaseT? = getFunc(dl!, f: "CCDHParametersRelease")
}
open class EC {
public static func generateKeyPair(_ keySize: Int) throws -> (Data, Data) {
var privKey: CCECCryptorRef? = nil
var pubKey: CCECCryptorRef? = nil
let status = CCECCryptorGeneratePair!(
keySize,
&pubKey,
&privKey)
guard status == noErr else { throw CCError(status) }
defer {
CCECCryptorRelease!(privKey!)
CCECCryptorRelease!(pubKey!)
}
let privKeyDER = try exportKey(privKey!, format: .binary, type: .keyPrivate)
let pubKeyDER = try exportKey(pubKey!, format: .binary, type: .keyPublic)
return (privKeyDER, pubKeyDER)
}
public static func getPublicKeyFromPrivateKey(_ privateKey: Data) throws -> Data {
let privKey = try importKey(privateKey, format: .binary, keyType: .keyPrivate)
defer { CCECCryptorRelease!(privKey) }
let pubKey = CCECCryptorGetPublicKeyFromPrivateKey!(privKey)
defer { CCECCryptorRelease!(pubKey) }
let pubKeyDER = try exportKey(pubKey, format: .binary, type: .keyPublic)
return pubKeyDER
}
public static func signHash(_ privateKey: Data, hash: Data) throws -> Data {
let privKey = try importKey(privateKey, format: .binary, keyType: .keyPrivate)
defer { CCECCryptorRelease!(privKey) }
var signedDataLength = 4096
var signedData = Data(count:signedDataLength)
let status = withUnsafePointers(hash, &signedData, {
hashBytes, signedDataBytes in
return CCECCryptorSignHash!(
privKey,
hashBytes, hash.count,
signedDataBytes, &signedDataLength)
})
guard status == noErr else { throw CCError(status) }
signedData.count = signedDataLength
return signedData
}
public static func verifyHash(_ publicKey: Data,
hash: Data,
signedData: Data) throws -> Bool {
let pubKey = try importKey(publicKey, format: .binary, keyType: .keyPublic)
defer { CCECCryptorRelease!(pubKey) }
var valid: UInt32 = 0
let status = withUnsafePointers(hash, signedData, { hashBytes, signedDataBytes in
return CCECCryptorVerifyHash!(
pubKey,
hashBytes, hash.count,
signedDataBytes, signedData.count,
&valid)
})
guard status == noErr else { throw CCError(status) }
return valid != 0
}
public static func computeSharedSecret(_ privateKey: Data,
publicKey: Data) throws -> Data {
let privKey = try importKey(privateKey, format: .binary, keyType: .keyPrivate)
let pubKey = try importKey(publicKey, format: .binary, keyType: .keyPublic)
defer {
CCECCryptorRelease!(privKey)
CCECCryptorRelease!(pubKey)
}
var outSize = 8192
var result = Data(count:outSize)
let status = result.withUnsafeMutableBytes { resultBytes -> OSStatus in
CCECCryptorComputeSharedSecret!(privKey, pubKey, resultBytes.baseAddress!, &outSize)
}
guard status == noErr else { throw CCError(status) }
result.count = outSize
return result
}
public struct KeyComponents {
public init(_ keySize: Int, _ x: Data, _ y: Data, _ d: Data) {
self.keySize = keySize
self.x = x
self.y = y
self.d = d
}
public var keySize: Int
public var x: Data
public var y: Data
public var d: Data
}
public static func getPublicKeyComponents(_ keyData: Data) throws -> KeyComponents {
let key = try importKey(keyData, format: .binary, keyType: .keyPublic)
defer { CCECCryptorRelease!(key) }
return try getKeyComponents(key)
}
public static func getPrivateKeyComponents(_ keyData: Data) throws -> KeyComponents {
let key = try importKey(keyData, format: .binary, keyType: .keyPrivate)
defer { CCECCryptorRelease!(key) }
return try getKeyComponents(key)
}
fileprivate static func getKeyComponents(_ key: CCECCryptorRef) throws -> KeyComponents {
var keySize = 0, xSize = 8192, ySize = 8192, dSize = 8192
var x = Data(count: xSize), y = Data(count: ySize), d = Data(count: dSize)
let status = withUnsafePointers(&x, &y, &d, { xBytes, yBytes, dBytes in
return CCECCryptorGetKeyComponents!(key, &keySize,
xBytes, &xSize,
yBytes, &ySize,
dBytes, &dSize)
})
guard status == noErr else { throw CCError(status) }
x.count = xSize
y.count = ySize
d.count = dSize
if getKeyType(key) == .keyPublic {
d.count = 0
}
return KeyComponents(keySize, x, y, d)
}
public static func createFromData(_ keySize: size_t, _ x: Data, _ y: Data) throws -> Data {
var pubKey: CCECCryptorRef? = nil
let status = withUnsafePointers(x, y, { xBytes, yBytes in
return CCECCryptorCreateFromData!(keySize, xBytes, x.count,
yBytes, y.count, &pubKey)
})
guard status == noErr else { throw CCError(status) }
defer { CCECCryptorRelease!(pubKey!) }
let pubKeyBin = try exportKey(pubKey!, format: .binary, type: .keyPublic)
return pubKeyBin
}
fileprivate static func importKey(_ key: Data, format: KeyExternalFormat,
keyType: KeyType) throws -> CCECCryptorRef {
var impKey: CCECCryptorRef? = nil
let status = key.withUnsafeBytes { keyBytes -> OSStatus in
CCECCryptorImportKey!(format.rawValue,
keyBytes.baseAddress!, key.count,
keyType.rawValue, &impKey)
}
guard status == noErr else { throw CCError(status) }
return impKey!
}
fileprivate static func exportKey(_ key: CCECCryptorRef, format: KeyExternalFormat,
type: KeyType) throws -> Data {
var expKeyLength = 8192
var expKey = Data(count:expKeyLength)
let status = expKey.withUnsafeMutableBytes { expKeyBytes -> OSStatus in
CCECCryptorExportKey!(
format.rawValue,
expKeyBytes.baseAddress!,
&expKeyLength,
type.rawValue,
key)
}
guard status == noErr else { throw CCError(status) }
expKey.count = expKeyLength
return expKey
}
fileprivate static func getKeyType(_ key: CCECCryptorRef) -> KeyType {
return KeyType(rawValue: CCECGetKeyType!(key))!
}
public static func available() -> Bool {
return CCECCryptorGeneratePair != nil &&
CCECCryptorImportKey != nil &&
CCECCryptorExportKey != nil &&
CCECCryptorRelease != nil &&
CCECCryptorSignHash != nil &&
CCECCryptorVerifyHash != nil &&
CCECCryptorComputeSharedSecret != nil &&
CCECCryptorGetKeyComponents != nil &&
CCECCryptorCreateFromData != nil &&
CCECGetKeyType != nil &&
CCECCryptorGetPublicKeyFromPrivateKey != nil
}
fileprivate enum KeyType: CCECKeyType {
case keyPublic = 0, keyPrivate
case blankPublicKey = 97, blankPrivateKey
case badKey = 99
}
fileprivate typealias CCECKeyType = UInt32
fileprivate typealias CCECKeyExternalFormat = UInt32
fileprivate enum KeyExternalFormat: CCECKeyExternalFormat {
case binary = 0, der
}
fileprivate typealias CCECCryptorRef = UnsafeRawPointer
fileprivate typealias CCECCryptorGeneratePairT = @convention(c) (
_ keySize: size_t ,
_ publicKey: UnsafeMutablePointer<CCECCryptorRef?>,
_ privateKey: UnsafeMutablePointer<CCECCryptorRef?>) -> CCCryptorStatus
fileprivate static let CCECCryptorGeneratePair: CCECCryptorGeneratePairT? =
getFunc(dl!, f: "CCECCryptorGeneratePair")
fileprivate typealias CCECCryptorImportKeyT = @convention(c) (
_ format: CCECKeyExternalFormat,
_ keyPackage: UnsafeRawPointer, _ keyPackageLen: size_t,
_ keyType: CCECKeyType, _ key: UnsafeMutablePointer<CCECCryptorRef?>) -> CCCryptorStatus
fileprivate static let CCECCryptorImportKey: CCECCryptorImportKeyT? =
getFunc(dl!, f: "CCECCryptorImportKey")
fileprivate typealias CCECCryptorExportKeyT = @convention(c) (
_ format: CCECKeyExternalFormat,
_ keyPackage: UnsafeRawPointer,
_ keyPackageLen: UnsafePointer<size_t>,
_ keyType: CCECKeyType, _ key: CCECCryptorRef) -> CCCryptorStatus
fileprivate static let CCECCryptorExportKey: CCECCryptorExportKeyT? =
getFunc(dl!, f: "CCECCryptorExportKey")
fileprivate typealias CCECCryptorReleaseT = @convention(c) (
_ key: CCECCryptorRef) -> Void
fileprivate static let CCECCryptorRelease: CCECCryptorReleaseT? =
getFunc(dl!, f: "CCECCryptorRelease")
fileprivate typealias CCECCryptorSignHashT = @convention(c)(
_ privateKey: CCECCryptorRef,
_ hashToSign: UnsafeRawPointer,
_ hashSignLen: size_t,
_ signedData: UnsafeMutableRawPointer,
_ signedDataLen: UnsafeMutablePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCECCryptorSignHash: CCECCryptorSignHashT? =
getFunc(dl!, f: "CCECCryptorSignHash")
fileprivate typealias CCECCryptorVerifyHashT = @convention(c)(
_ publicKey: CCECCryptorRef,
_ hash: UnsafeRawPointer, _ hashLen: size_t,
_ signedData: UnsafeRawPointer, _ signedDataLen: size_t,
_ valid: UnsafeMutablePointer<UInt32>) -> CCCryptorStatus
fileprivate static let CCECCryptorVerifyHash: CCECCryptorVerifyHashT? =
getFunc(dl!, f: "CCECCryptorVerifyHash")
fileprivate typealias CCECCryptorComputeSharedSecretT = @convention(c)(
_ privateKey: CCECCryptorRef,
_ publicKey: CCECCryptorRef,
_ out: UnsafeMutableRawPointer,
_ outLen: UnsafeMutablePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCECCryptorComputeSharedSecret: CCECCryptorComputeSharedSecretT? =
getFunc(dl!, f: "CCECCryptorComputeSharedSecret")
fileprivate typealias CCECCryptorGetKeyComponentsT = @convention(c)(
_ ecKey: CCECCryptorRef,
_ keySize: UnsafeMutablePointer<Int>,
_ qX: UnsafeMutableRawPointer,
_ qXLength: UnsafeMutablePointer<Int>,
_ qY: UnsafeMutableRawPointer,
_ qYLength: UnsafeMutablePointer<Int>,
_ d: UnsafeMutableRawPointer?,
_ dLength: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate static let CCECCryptorGetKeyComponents: CCECCryptorGetKeyComponentsT? =
getFunc(dl!, f: "CCECCryptorGetKeyComponents")
fileprivate typealias CCECCryptorCreateFromDataT = @convention(c)(
_ keySize: size_t,
_ qX: UnsafeRawPointer,
_ qXLength: size_t,
_ qY: UnsafeRawPointer,
_ qYLength: size_t,
_ publicKey: UnsafeMutablePointer<CCECCryptorRef?>) -> CCCryptorStatus
fileprivate static let CCECCryptorCreateFromData: CCECCryptorCreateFromDataT? =
getFunc(dl!, f: "CCECCryptorCreateFromData")
fileprivate typealias CCECGetKeyTypeT = @convention(c) (
_ key: CCECCryptorRef) -> CCECKeyType
fileprivate static let CCECGetKeyType: CCECGetKeyTypeT? =
getFunc(dl!, f: "CCECGetKeyType")
fileprivate typealias CCECCryptorGetPublicKeyFromPrivateKeyT = @convention(c) (
_ key: CCECCryptorRef) -> CCECCryptorRef
fileprivate static let CCECCryptorGetPublicKeyFromPrivateKey: CCECCryptorGetPublicKeyFromPrivateKeyT? =
getFunc(dl!, f: "CCECCryptorGetPublicKeyFromPrivateKey")
}
open class CRC {
public typealias CNcrc = UInt32
public enum Mode: CNcrc {
case crc8 = 10,
crc8ICODE = 11,
crc8ITU = 12,
crc8ROHC = 13,
crc8WCDMA = 14,
crc16 = 20,
crc16CCITTTrue = 21,
crc16CCITTFalse = 22,
crc16USB = 23,
crc16XMODEM = 24,
crc16DECTR = 25,
crc16DECTX = 26,
crc16ICODE = 27,
crc16VERIFONE = 28,
crc16A = 29,
crc16B = 30,
crc16Fletcher = 31,
crc32Adler = 40,
crc32 = 41,
crc32CASTAGNOLI = 42,
crc32BZIP2 = 43,
crc32MPEG2 = 44,
crc32POSIX = 45,
crc32XFER = 46,
crc64ECMA182 = 60
}
public static func crc(_ input: Data, mode: Mode) throws -> UInt64 {
var result: UInt64 = 0
let status = input.withUnsafeBytes { inputBytes -> OSStatus in
CNCRC!(
mode.rawValue,
inputBytes.baseAddress!, input.count,
&result)
}
guard status == noErr else {
throw CCError(status)
}
return result
}
public static func available() -> Bool {
return CNCRC != nil
}
fileprivate typealias CNCRCT = @convention(c) (
_ algorithm: CNcrc,
_ input: UnsafeRawPointer, _ inputLen: size_t,
_ result: UnsafeMutablePointer<UInt64>) -> CCCryptorStatus
fileprivate static let CNCRC: CNCRCT? = getFunc(dl!, f: "CNCRC")
}
open class CMAC {
public static func AESCMAC(_ data: Data, key: Data) -> Data {
var result = Data(count: 16)
withUnsafePointers(key, data, &result, { keyBytes, dataBytes, resultBytes in
CCAESCmac!(keyBytes,
dataBytes, data.count,
resultBytes)
})
return result
}
public static func available() -> Bool {
return CCAESCmac != nil
}
fileprivate typealias CCAESCmacT = @convention(c) (
_ key: UnsafeRawPointer,
_ data: UnsafeRawPointer, _ dataLen: size_t,
_ macOut: UnsafeMutableRawPointer) -> Void
fileprivate static let CCAESCmac: CCAESCmacT? = getFunc(dl!, f: "CCAESCmac")
}
open class KeyDerivation {
public typealias CCPseudoRandomAlgorithm = UInt32
public enum PRFAlg: CCPseudoRandomAlgorithm {
case sha1 = 1, sha224, sha256, sha384, sha512
var cc: CC.HMACAlg {
switch self {
case .sha1: return .sha1
case .sha224: return .sha224
case .sha256: return .sha256
case .sha384: return .sha384
case .sha512: return .sha512
}
}
}
public static func PBKDF2(_ password: String, salt: Data,
prf: PRFAlg, rounds: UInt32) throws -> Data {
var result = Data(count:prf.cc.digestLength)
let rescount = result.count
let passwData = password.data(using: String.Encoding.utf8)!
let status = withUnsafePointers(passwData, salt, &result, {
passwDataBytes, saltBytes, resultBytes in
return CCKeyDerivationPBKDF!(PBKDFAlgorithm.pbkdf2.rawValue,
passwDataBytes, passwData.count,
saltBytes, salt.count,
prf.rawValue, rounds,
resultBytes, rescount)
})
guard status == noErr else { throw CCError(status) }
return result
}
public static func available() -> Bool {
return CCKeyDerivationPBKDF != nil
}
fileprivate typealias CCPBKDFAlgorithm = UInt32
fileprivate enum PBKDFAlgorithm: CCPBKDFAlgorithm {
case pbkdf2 = 2
}
fileprivate typealias CCKeyDerivationPBKDFT = @convention(c) (
_ algorithm: CCPBKDFAlgorithm,
_ password: UnsafeRawPointer, _ passwordLen: size_t,
_ salt: UnsafeRawPointer, _ saltLen: size_t,
_ prf: CCPseudoRandomAlgorithm, _ rounds: uint,
_ derivedKey: UnsafeMutableRawPointer, _ derivedKeyLen: size_t) -> CCCryptorStatus
fileprivate static let CCKeyDerivationPBKDF: CCKeyDerivationPBKDFT? =
getFunc(dl!, f: "CCKeyDerivationPBKDF")
}
open class KeyWrap {
fileprivate static let rfc3394IVData: [UInt8] = [0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6]
public static let rfc3394IV = Data(bytes: rfc3394IVData.withUnsafeBufferPointer { $0.baseAddress! },
count:rfc3394IVData.count)
public static func SymmetricKeyWrap(_ iv: Data,
kek: Data,
rawKey: Data) throws -> Data {
let alg = WrapAlg.aes.rawValue
var wrappedKeyLength = CCSymmetricWrappedSize!(alg, rawKey.count)
var wrappedKey = Data(count:wrappedKeyLength)
let status = withUnsafePointers(iv, kek, rawKey, &wrappedKey, {
ivBytes, kekBytes, rawKeyBytes, wrappedKeyBytes in
return CCSymmetricKeyWrap!(
alg,
ivBytes, iv.count,
kekBytes, kek.count,
rawKeyBytes, rawKey.count,
wrappedKeyBytes, &wrappedKeyLength)
})
guard status == noErr else { throw CCError(status) }
wrappedKey.count = wrappedKeyLength
return wrappedKey
}
public static func SymmetricKeyUnwrap(_ iv: Data,
kek: Data,
wrappedKey: Data) throws -> Data {
let alg = WrapAlg.aes.rawValue
var rawKeyLength = CCSymmetricUnwrappedSize!(alg, wrappedKey.count)
var rawKey = Data(count:rawKeyLength)
let status = withUnsafePointers(iv, kek, wrappedKey, &rawKey, {
ivBytes, kekBytes, wrappedKeyBytes, rawKeyBytes in
return CCSymmetricKeyUnwrap!(
alg,
ivBytes, iv.count,
kekBytes, kek.count,
wrappedKeyBytes, wrappedKey.count,
rawKeyBytes, &rawKeyLength)
})
guard status == noErr else { throw CCError(status) }
rawKey.count = rawKeyLength
return rawKey
}
public static func available() -> Bool {
return CCSymmetricKeyWrap != nil &&
CCSymmetricKeyUnwrap != nil &&
CCSymmetricWrappedSize != nil &&
CCSymmetricUnwrappedSize != nil
}
fileprivate enum WrapAlg: CCWrappingAlgorithm {
case aes = 1
}
fileprivate typealias CCWrappingAlgorithm = UInt32
fileprivate typealias CCSymmetricKeyWrapT = @convention(c) (
_ algorithm: CCWrappingAlgorithm,
_ iv: UnsafeRawPointer, _ ivLen: size_t,
_ kek: UnsafeRawPointer, _ kekLen: size_t,
_ rawKey: UnsafeRawPointer, _ rawKeyLen: size_t,
_ wrappedKey: UnsafeMutableRawPointer,
_ wrappedKeyLen: UnsafePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCSymmetricKeyWrap: CCSymmetricKeyWrapT? = getFunc(dl!, f: "CCSymmetricKeyWrap")
fileprivate typealias CCSymmetricKeyUnwrapT = @convention(c) (
_ algorithm: CCWrappingAlgorithm,
_ iv: UnsafeRawPointer, _ ivLen: size_t,
_ kek: UnsafeRawPointer, _ kekLen: size_t,
_ wrappedKey: UnsafeRawPointer, _ wrappedKeyLen: size_t,
_ rawKey: UnsafeMutableRawPointer,
_ rawKeyLen: UnsafePointer<size_t>) -> CCCryptorStatus
fileprivate static let CCSymmetricKeyUnwrap: CCSymmetricKeyUnwrapT? =
getFunc(dl!, f: "CCSymmetricKeyUnwrap")
fileprivate typealias CCSymmetricWrappedSizeT = @convention(c) (
_ algorithm: CCWrappingAlgorithm,
_ rawKeyLen: size_t) -> size_t
fileprivate static let CCSymmetricWrappedSize: CCSymmetricWrappedSizeT? =
getFunc(dl!, f: "CCSymmetricWrappedSize")
fileprivate typealias CCSymmetricUnwrappedSizeT = @convention(c) (
_ algorithm: CCWrappingAlgorithm,
_ wrappedKeyLen: size_t) -> size_t
fileprivate static let CCSymmetricUnwrappedSize: CCSymmetricUnwrappedSizeT? =
getFunc(dl!, f: "CCSymmetricUnwrappedSize")
}
}
private func getFunc<T>(_ from: UnsafeMutableRawPointer, f: String) -> T? {
let sym = dlsym(from, f)
guard sym != nil else {
return nil
}
return unsafeBitCast(sym, to: T.self)
}
extension Data {
/// Create hexadecimal string representation of Data object.
///
/// - returns: String representation of this Data object.
public func hexadecimalString() -> String {
return self.withUnsafeBytes { data -> String in
var hexstr = String()
for i in data.bindMemory(to: UInt8.self) {
hexstr += String(format: "%02X", i)
}
return hexstr
}
}
public func arrayOfBytes() -> [UInt8] {
let count = self.count / MemoryLayout<UInt8>.size
var bytesArray = [UInt8](repeating: 0, count: count)
self.copyBytes(to: &bytesArray, count: count * MemoryLayout<UInt8>.size)
return bytesArray
}
fileprivate var bytesView: BytesView { return BytesView(self) }
fileprivate func bytesViewRange(_ range: NSRange) -> BytesView {
return BytesView(self, range: range)
}
fileprivate struct BytesView: Collection {
// The view retains the Data. That's on purpose.
// Data doesn't retain the view, so there's no loop.
let data: Data
init(_ data: Data) {
self.data = data
self.startIndex = 0
self.endIndex = data.count
}
init(_ data: Data, range: NSRange ) {
self.data = data
self.startIndex = range.location
self.endIndex = range.location + range.length
}
subscript (position: Int) -> UInt8 {
return data.withUnsafeBytes({ dataBytes -> UInt8 in
dataBytes.bindMemory(to: UInt8.self)[position]
})
}
subscript (bounds: Range<Int>) -> Data {
return data.subdata(in: bounds)
}
fileprivate func formIndex(after i: inout Int) {
i += 1
}
fileprivate func index(after i: Int) -> Int {
return i + 1
}
var startIndex: Int
var endIndex: Int
var length: Int { return endIndex - startIndex }
}
}
extension String {
/// Create Data from hexadecimal string representation
///
/// This takes a hexadecimal representation and creates a Data object. Note, if the string has
/// any spaces, those are removed. Also if the string started with a '<' or ended with a '>',
/// those are removed, too. This does no validation of the string to ensure it's a valid
/// hexadecimal string
///
/// The use of `strtoul` inspired by Martin R at http://stackoverflow.com/a/26284562/1271826
///
/// - returns: Data represented by this hexadecimal string.
/// Returns nil if string contains characters outside the 0-9 and a-f range.
public func dataFromHexadecimalString() -> Data? {
let trimmedString = self.trimmingCharacters(
in: CharacterSet(charactersIn: "<> ")).replacingOccurrences(
of: " ", with: "")
// make sure the cleaned up string consists solely of hex digits,
// and that we have even number of them
let regex = try! NSRegularExpression(pattern: "^[0-9a-f]*$", options: .caseInsensitive)
let found = regex.firstMatch(in: trimmedString, options: [],
range: NSRange(location: 0,
length: trimmedString.count))
guard found != nil &&
found?.range.location != NSNotFound &&
trimmedString.count % 2 == 0 else {
return nil
}
// everything ok, so now let's build Data
var data = Data(capacity: trimmedString.count / 2)
var index: String.Index? = trimmedString.startIndex
while let i = index {
let byteString = String(trimmedString[i ..< trimmedString.index(i, offsetBy: 2)])
let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
data.append([num] as [UInt8], count: 1)
index = trimmedString.index(i, offsetBy: 2, limitedBy: trimmedString.endIndex)
if index == trimmedString.endIndex { break }
}
return data
}
}
fileprivate func withUnsafePointers<A0, A1, Result>(
_ arg0: Data,
_ arg1: Data,
_ body: (
UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeBytes { p0 -> Result in
return try arg1.withUnsafeBytes { p1 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!)
}
}
}
fileprivate func withUnsafePointers<A0, A1, Result>(
_ arg0: Data,
_ arg1: inout Data,
_ body: (
UnsafePointer<A0>,
UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeBytes { p0 -> Result in
return try arg1.withUnsafeMutableBytes { p1 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!)
}
}
}
fileprivate func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: Data,
_ arg1: Data,
_ arg2: inout Data,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafeMutablePointer<A2>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeBytes { p0 -> Result in
return try arg1.withUnsafeBytes { p1 -> Result in
return try arg2.withUnsafeMutableBytes { p2 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!,
p2.bindMemory(to: A2.self).baseAddress!)
}
}
}
}
fileprivate func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout Data,
_ arg1: inout Data,
_ arg2: inout Data,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeMutableBytes { p0 -> Result in
return try arg1.withUnsafeMutableBytes { p1 -> Result in
return try arg2.withUnsafeMutableBytes { p2 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!,
p2.bindMemory(to: A2.self).baseAddress!)
}
}
}
}
fileprivate func withUnsafePointers<A0, A1, A2, A3, Result>(
_ arg0: Data,
_ arg1: Data,
_ arg2: Data,
_ arg3: inout Data,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>,
UnsafeMutablePointer<A3>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeBytes { p0 -> Result in
return try arg1.withUnsafeBytes { p1 -> Result in
return try arg2.withUnsafeBytes { p2 -> Result in
return try arg3.withUnsafeMutableBytes { p3 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!,
p2.bindMemory(to: A2.self).baseAddress!,
p3.bindMemory(to: A3.self).baseAddress!)
}
}
}
}
}
fileprivate func withUnsafePointers<A0, A1, A2, A3, A4, A5, Result>(
_ arg0: Data,
_ arg1: Data,
_ arg2: Data,
_ arg3: Data,
_ arg4: inout Data,
_ arg5: inout Data,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>,
UnsafePointer<A3>,
UnsafeMutablePointer<A4>,
UnsafeMutablePointer<A5>) throws -> Result
) rethrows -> Result {
return try arg0.withUnsafeBytes { p0 -> Result in
return try arg1.withUnsafeBytes { p1 -> Result in
return try arg2.withUnsafeBytes { p2 -> Result in
return try arg3.withUnsafeBytes { p3 -> Result in
return try arg4.withUnsafeMutableBytes { p4 -> Result in
return try arg5.withUnsafeMutableBytes { p5 -> Result in
return try body(p0.bindMemory(to: A0.self).baseAddress!,
p1.bindMemory(to: A1.self).baseAddress!,
p2.bindMemory(to: A2.self).baseAddress!,
p3.bindMemory(to: A3.self).baseAddress!,
p4.bindMemory(to: A4.self).baseAddress!,
p5.bindMemory(to: A5.self).baseAddress!)
}
}
}
}
}
}
}
| 31.178144 | 177 | 0.697184 |
260ed33bd869b3a903a89f1c8722b2820c69b821 | 250 | //
// DashboardCellType.swift
// AloBasta
//
// Created by Agus Cahyono on 17/10/19.
// Copyright © 2019 Agus Cahyono. All rights reserved.
//
import Foundation
enum DashboardCellType: String {
case listDoctor = "ListDocterTableViewCell"
}
| 17.857143 | 55 | 0.716 |
75b6cd8876fa57ca7f7cf1c9268058089505e1d6 | 5,039 | /* Copyright Airship and Contributors */
import Foundation
import UIKit
#if canImport(AirshipCore)
import AirshipCore
#endif
/**
* Chat style.
*/
@objc(UAChatStyle)
public class ChatStyle : NSObject {
/**
* The title text.
*/
@objc public var title: String?
/**
* The title font.
*/
@objc public var titleFont: UIFont?
/**
* The title color.
*/
@objc public var titleColor: UIColor?
/**
* The outgoing text color.
*/
@objc public var outgoingTextColor: UIColor?
/**
* The incoming text color.
*/
@objc public var incomingTextColor: UIColor?
/**
* The message text font.
*/
@objc public var messageTextFont: UIFont?
/**
* The outgoing chat bubble color.
*/
@objc public var outgoingChatBubbleColor: UIColor?
/**
* The incoming chat bubble color.
*/
@objc public var incomingChatBubbleColor: UIColor?
/**
* The date color.
*/
@objc public var dateColor: UIColor?
/**
* The date font.
*/
@objc public var dateFont: UIFont?
/**
* The background color.
*/
@objc public var backgroundColor: UIColor?
/**
* The navigation bar color.
*/
@objc public var navigationBarColor: UIColor?
/**
* The tint color.
*/
@objc public var tintColor: UIColor?
/**
* Chat style initializer
*/
public override init() {
super.init()
}
/**
* Chat style initializer for parsing from a plist.
*
* @param file The plist file to read from.
*/
public init(file: String) {
super.init()
if let path = Bundle.main.path(forResource: file, ofType: "plist") {
do {
var format = PropertyListSerialization.PropertyListFormat.xml
let xml = FileManager.default.contents(atPath: path)!
let styleDict = try PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: &format) as! [String:AnyObject]
let normalized = normalize(keyedValues: styleDict)
setValuesForKeys(normalized)
} catch {
AirshipLogger.error("Error reading chat style plist: \(error)")
}
} else {
AirshipLogger.error("Unable to find chat plist file: \(file)")
}
}
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
// Do not crash on undefined keys
AirshipLogger.debug("Ignoring invalid chat style key: \(key)")
}
private func normalize(keyedValues: [String : AnyObject]) -> [String : AnyObject] {
var normalized: [String : AnyObject] = [:]
for (key, value) in keyedValues {
var normalizedValue: AnyObject?
// Trim whitespace
if let stringValue = value as? String {
normalizedValue = stringValue.trimmingCharacters(in: .whitespaces) as AnyObject
}
// Normalize colors
if key.hasSuffix("Color") {
if let colorString = value as? String {
normalizedValue = createColor(string: colorString)
normalized[key] = normalizedValue
}
continue
}
// Normalize fonts
if key.hasSuffix("Font") {
if let fontDict = value as? [String : String] {
normalizedValue = createFont(dict: fontDict)
normalized[key] = normalizedValue
}
continue
}
normalized[key] = normalizedValue
}
return normalized
}
private func createColor(string: String) -> UIColor? {
let hexColor = ColorUtils.color(string)
let namedColor = UIColor(named: string)
guard hexColor != nil || namedColor != nil else {
AirshipLogger.error("Color must be a valid string representing either a valid color hexidecimal or a named color corresponding to a color asset in the main bundle.")
return nil
}
return namedColor != nil ? namedColor : hexColor
}
private func createFont(dict: [String : String]) -> UIFont? {
let name = dict["fontName"]
let size = dict["fontSize"]
guard name != nil && size != nil else {
AirshipLogger.error("Font name must be a valid string under the key \"fontName\". Font size must be a valid string under the key \"fontSize\"")
return nil
}
let sizeNum = CGFloat(Double(size!) ?? 0)
guard sizeNum > 0 else {
AirshipLogger.error("Font size must represent a double greater than 0")
return nil
}
let font = UIFont(name: name!, size: sizeNum)
guard font != nil else {
AirshipLogger.error("Font must exist in app bundle")
return nil;
}
return font
}
}
| 26.108808 | 177 | 0.568367 |
4851bae2091fcf4ccb2a5f55aedab6f603d19025 | 8,923 | /* Copyright 2018 JDCLOUD.COM
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.
操作列表
云解析OpenAPI操作列表接口
OpenAPI spec version: v2
Contact:
NOTE: This class is auto generated by the jdcloud code generator program.
*/
import Foundation
import JDCloudSDKCore
/// 获取用户所属的主域名列表。
/// 请在调用域名相关的接口之前,调用此接口获取相关的domainId和domainName。
/// 主域名的相关概念,请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/product-overview">云解析文档</a>
///
public class DescribeDomainsExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain")
}
}
/// 添加主域名
/// 如何添加免费域名,详细情况请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/domainadd">文档</a>
/// 添加收费域名,请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/purchase-process">文档</a>,
/// 添加收费域名前,请确保用户的京东云账户有足够的资金支付,Openapi接口回返回订单号,可以用此订单号向计费系统查阅详情。
///
public class CreateDomainExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain")
}
}
/// 修改主域名
public class ModifyDomainExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "PUT", url: "/regions/{regionId}/domain/{domainId}")
}
}
/// 删除主域名
public class DeleteDomainExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "DELETE", url: "/regions/{regionId}/domain/{domainId}")
}
}
/// 查看主域名的解析次数
public class DescribeDomainQueryCountExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/queryCount")
}
}
/// 查看域名的查询流量
public class DescribeDomainQueryTrafficExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/queryTraffic")
}
}
/// 查看主域名的监控项的配置以及状态
public class DescribeMonitorExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/monitor")
}
}
/// 添加子域名的监控项,默认把子域名的所有监控项都添加上监控
public class CreateMonitorExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/monitor")
}
}
/// 域名的监控项修改
public class ModifyMonitorExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "PUT", url: "/regions/{regionId}/domain/{domainId}/monitor")
}
}
/// 查询子域名的可用监控对象
public class DescribeMonitorTargetExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/monitorTarget")
}
}
/// 添加子域名的某些特定监控对象为监控项
public class CreateMonitorTargetExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/monitorTarget")
}
}
/// 监控项的操作集合,包括:暂停,启动, 手动恢复, 手动切换
public class ModifyMonitorStatusExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "PUT", url: "/regions/{regionId}/domain/{domainId}/monitor/{monitorId}/status")
}
}
/// 监控项的删除
public class DeleteMonitorExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "DELETE", url: "/regions/{regionId}/domain/{domainId}/monitor/{monitorId}")
}
}
/// 主域名的监控项的报警信息
public class DescribeMonitorAlarmExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/monitorAlarm")
}
}
/// 查询主域名的解析记录。
/// 在使用解析记录相关的接口之前,请调用此接口获取解析记录的列表。
///
public class DescribeResourceRecordExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/ResourceRecord")
}
}
/// 添加主域名的解析记录
public class CreateResourceRecordExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/ResourceRecord")
}
}
/// 修改主域名的某个解析记录
public class ModifyResourceRecordExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "PUT", url: "/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}")
}
}
/// 删除主域名下的解析记录
public class DeleteResourceRecordExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "DELETE", url: "/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}")
}
}
/// 启用、停用主域名下的解析记录
public class ModifyResourceRecordStatusExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "PUT", url: "/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}/status")
}
}
/// 查询云解析所有的基础解析线路。
/// 在使用解析线路的参数之前,请调用此接口获取解析线路的ID。
///
public class DescribeViewTreeExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/viewTree")
}
}
/// 同一个主域名下,批量新增或者批量更新导入解析记录。
/// 如果解析记录的ID为0,是新增解析记录,如果不为0,则是更新解析记录。
///
public class BatchSetResourceRecordsExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/BatchSetResourceRecords")
}
}
/// 查询主域名的自定义解析线路
public class DescribeUserViewExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/UserView")
}
}
/// 添加主域名的自定义解析线路
public class CreateUserViewExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/UserView")
}
}
/// 删除主域名的自定义解析线路
public class DeleteUserViewExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/DeleteUserView")
}
}
/// 查询主域名的自定义解析线路的IP段
public class DescribeUserViewIPExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/domain/{domainId}/UserViewIP")
}
}
/// 添加主域名的自定义解析线路的IP段
public class CreateUserViewIPExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/UserViewIP")
}
}
/// 删除主域名的自定义解析线路的IP段
public class DeleteUserViewIPExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "POST", url: "/regions/{regionId}/domain/{domainId}/DeleteUserViewIP")
}
}
/// 查看用户在云解析服务下的操作记录
public class DescribeActionLogExecutor:JDCloudExecutor {
public init(jdCloudClient: JDCloudClient) {
super.init(jdCloudClient: jdCloudClient, method: "GET", url: "/regions/{regionId}/actionLog")
}
}
| 33.671698 | 150 | 0.706265 |
502546e12aca2e730b8ddd1299d61b50e36a1ef5 | 7,156 | import Foundation
import RxCocoa
import RxSwift
import TokenDSDK
protocol CreateOfferBusinessLogic {
typealias Event = CreateOffer.Event
func onViewDidLoadSync(request: Event.ViewDidLoadSync.Request)
func onFieldEditing(request: Event.FieldEditing.Request)
func onButtonAction(request: Event.ButtonAction.Request)
}
extension CreateOffer {
typealias BusinessLogic = CreateOfferBusinessLogic
class Interactor {
typealias Event = CreateOffer.Event
// MARK: - Private properties
private var sceneModel: Model.SceneModel
private let presenter: PresentationLogic
private let accountId: String
private let feeLoader: FeeLoaderProtocol
private let loadingStatus: BehaviorRelay<Model.LoadingStatus> = BehaviorRelay(value: .loaded)
private let disposeBag: DisposeBag = DisposeBag()
init(
presenter: PresentationLogic,
accountId: String,
sceneModel: Model.SceneModel,
feeLoader: FeeLoaderProtocol
) {
self.presenter = presenter
self.sceneModel = sceneModel
self.accountId = accountId
self.feeLoader = feeLoader
}
private enum LoadFeesResult {
case succeeded(fee: Model.FeeModel)
case failed(CreateOfferFeeLoaderResult.FeeLoaderError)
}
private func loadFee(
amount: Decimal,
asset: String,
completion: @escaping (LoadFeesResult) -> Void
) {
self.feeLoader.loadFee(
accountId: self.accountId,
asset: asset,
amount: amount,
completion: { (result) in
switch result {
case .succeeded(let fee):
completion(.succeeded(fee: fee))
case .failed(let error):
completion(.failed(error))
}
})
}
enum HandleActionResult {
case offer(Model.CreateOfferModel)
case error(String)
}
private func handleAction(
isBuy: Bool,
completion: @escaping (HandleActionResult) -> Void
) {
guard let amount = self.sceneModel.amount,
amount > 0,
let price = self.sceneModel.price,
price > 0
else {
completion(.error(Localized(.seems_like_some_fields_are_empty)))
return
}
self.loadFee(
amount: amount * price,
asset: self.sceneModel.quoteAsset
) { [weak self] (result) in
guard let strongSelf = self else { return }
switch result {
case .succeeded(let fee):
let offer = Model.CreateOfferModel(
baseAsset: strongSelf.sceneModel.baseAsset,
quoteAsset: strongSelf.sceneModel.quoteAsset,
isBuy: isBuy,
amount: amount,
price: price,
fee: fee.percent
)
completion(.offer(offer))
case .failed(let errors):
completion(.error(errors.localizedDescription))
}
}
}
private func observeLoadingStatus() {
self.loadingStatus
.subscribe(onNext: { [weak self] (status) in
let response = status
self?.presenter.presentLoadingStatusDidChange(response: response)
})
.disposed(by: self.disposeBag)
}
}
}
extension CreateOffer.Interactor: CreateOffer.BusinessLogic {
func onViewDidLoadSync(request: Event.ViewDidLoadSync.Request) {
self.observeLoadingStatus()
let total = self.totalPrice()
let price = CreateOffer.Model.Amount(
value: self.sceneModel.price,
asset: self.sceneModel.quoteAsset
)
let amount = CreateOffer.Model.Amount(
value: self.sceneModel.amount,
asset: self.sceneModel.baseAsset
)
let response = Event.ViewDidLoadSync.Response(
price: price,
amount: amount,
total: total
)
self.presenter.presentViewDidLoadSync(response: response)
}
func onFieldEditing(request: Event.FieldEditing.Request) {
switch request.field.type {
case .price:
self.sceneModel.price = request.field.value
case .amount:
self.sceneModel.amount = request.field.value
}
let total = self.totalPrice()
let response = Event.FieldEditing.Response(total: total)
self.presenter.presentFieldEditing(response: response)
let stateDidChangeResponse = Event.FieldStateDidChange.Response(
priceFieldIsFilled: self.checkFieldValue(value: self.sceneModel.price),
amountFieldIsFilled: self.checkFieldValue(value: self.sceneModel.amount)
)
self.presenter.presentFieldStateDidChange(response: stateDidChangeResponse)
}
func onButtonAction(request: Event.ButtonAction.Request) {
let isBuy: Bool = {
switch request.type {
case .buy:
return true
case .sell:
return false
}
}()
self.loadingStatus.accept(.loading)
self.handleAction(
isBuy: isBuy,
completion: { [weak self] (result) in
self?.loadingStatus.accept(.loaded)
switch result {
case .offer(let offer):
let response = Event.ButtonAction.Response.offer(offer)
self?.presenter.presentButtonAction(response: response)
case .error(let error):
let response = Event.ButtonAction.Response.error(error)
self?.presenter.presentButtonAction(response: response)
}
})
}
}
extension CreateOffer.Interactor {
private func totalPrice() -> CreateOffer.Model.Amount {
let total = self.countTotal(
price: self.sceneModel.price,
amount: self.sceneModel.amount
)
let amount = CreateOffer.Model.Amount(
value: total,
asset: self.sceneModel.quoteAsset
)
return amount
}
private func countTotal(price: Decimal?, amount: Decimal?) -> Decimal {
let result = (price ?? 0) * (amount ?? 0)
return result
}
private func checkFieldValue(value: Decimal?) -> Bool {
return value != nil && value ?? 0 > 0
}
}
| 33.283721 | 101 | 0.535634 |
7a9a0b40e31e32068688e441965dbb5658981af1 | 2,205 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct CloudErrorBodyData : CloudErrorBodyProtocol {
public var code: String?
public var message: String?
public var target: String?
public var details: [CloudErrorBodyProtocol?]?
enum CodingKeys: String, CodingKey {case code = "code"
case message = "message"
case target = "target"
case details = "details"
}
public init() {
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.code) {
self.code = try container.decode(String?.self, forKey: .code)
}
if container.contains(.message) {
self.message = try container.decode(String?.self, forKey: .message)
}
if container.contains(.target) {
self.target = try container.decode(String?.self, forKey: .target)
}
if container.contains(.details) {
self.details = try container.decode([CloudErrorBodyData?]?.self, forKey: .details)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.code != nil {try container.encode(self.code, forKey: .code)}
if self.message != nil {try container.encode(self.message, forKey: .message)}
if self.target != nil {try container.encode(self.target, forKey: .target)}
if self.details != nil {try container.encode(self.details as! [CloudErrorBodyData?]?, forKey: .details)}
}
}
extension DataFactory {
public static func createCloudErrorBodyProtocol() -> CloudErrorBodyProtocol {
return CloudErrorBodyData()
}
}
| 38.017241 | 119 | 0.676644 |
28d3be65c598f4c2d91825c5572384ada973a7e7 | 209 | // 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<d where h:A{class a{class B:a
| 34.833333 | 87 | 0.755981 |
61887ecb7658d938081d86c7cb6d4723f302db6b | 642 | //
// SearchAPI.swift
// BAEPPO
//
// Created by Ethan on 2021/03/06.
//
import Foundation
import Moya
enum SearchAPI {
case sample
}
extension SearchAPI: TargetType {
var sampleData: Data { Data() }
var headers: [String : String]? { ["accept": "application/json", "Content-Type": "application/json"] }
var baseURL: URL { URL(string: "\(Network.baseURL)/search")! }
var path: String { "/" }
var method: Moya.Method {
switch self {
default:
return .get
}
}
var task: Task {
switch self {
default:
return .requestPlain
}
}
}
| 16.894737 | 106 | 0.556075 |
72c747352bce2881f876c3a189ec5481dcbc51af | 1,483 | /*
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 400
*/
class Solution {
func rob(_ nums: [Int]) -> Int {
if nums.isEmpty {
return 0
} else if nums.count == 1 {
return nums[0]
} else if nums.count == 2{
return max(nums[0], nums[1])
}
var dp1 = nums[0]
var dp2 = max(nums[0], nums[1])
for i in 2..<nums.count {
let amt = nums[i]
if i % 2 == 0 {
dp1 = max(dp1 + amt, dp2)
} else {
dp2 = max(dp2 + amt, dp1)
}
}
return max(dp1, dp2)
}
} | 30.265306 | 337 | 0.593392 |
0ee60f5f61f2761918d1a8417316f61b81c2616a | 456 | // 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
enum S<h : T where S.Iterator.E == compose() {
protocol a
| 41.454545 | 79 | 0.743421 |
ddf55f3a6403eb12dc8e7900128023ed68051a17 | 36,579 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@inlinable
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_internalInvariant(alignment > 0)
_internalInvariant(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@inlinable
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@inlinable
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_internalInvariant(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Use this function only to convert the instance passed as `x` to a
/// layout-compatible type when conversion through other means is not
/// possible. Common conversions supported by the Swift standard library
/// include the following:
///
/// - Value conversion from one integer type to another. Use the destination
/// type's initializer or the `numericCast(_:)` function.
/// - Bitwise conversion from one integer type to another. Use the destination
/// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer.
/// - Conversion from a pointer to an integer value with the bit pattern of the
/// pointer's address in memory, or vice versa. Use the `init(bitPattern:)`
/// initializer for the destination type.
/// - Casting an instance of a reference type. Use the casting operators (`as`,
/// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@inlinable // unsafe-performance
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"Can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// Returns `x` as its concrete type `U`.
///
/// This cast can be useful for dispatching to specializations of generic
/// functions.
///
/// - Requires: `x` has type `U`.
@_transparent
public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U {
_precondition(T.self == expectedType, "_identityCast to wrong type")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@usableFromInline @_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return !(lhs == rhs)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.RawPointer, rhs: Builtin.RawPointer
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether two types are identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the
/// same type; otherwise, `false`.
@inlinable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
switch (t0, t1) {
case (.none, .none): return true
case let (.some(ty0), .some(ty1)):
return Bool(Builtin.is_same_metatype(ty0, ty1))
default: return false
}
}
/// Returns a Boolean value indicating whether two types are not identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if
/// they represent different types; otherwise, `false`.
@inlinable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@usableFromInline @_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@usableFromInline @_transparent
internal func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@usableFromInline
@_silgen_name("_swift_isClassOrObjCExistentialType")
internal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@inlinable
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// Returns the given instance cast unconditionally to the specified type.
///
/// The instance passed as `x` must be an instance of type `T`.
///
/// Use this function instead of `unsafeBitcast(_:to:)` because this function
/// is more restrictive and still performs a check in debug builds. In -O
/// builds, no test is performed to ensure that `x` actually has the dynamic
/// type `T`.
///
/// - Warning: This function trades safety for performance. Use
/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always
/// evaluates to `true`, and only after `x as! T` has proven to be a
/// performance problem.
///
/// - Parameters:
/// - x: An instance to cast to type `T`.
/// - type: The type `T` to which `x` is cast.
/// - Returns: The instance `x`, cast to type `T`.
@_transparent
public func unsafeDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@_transparent
public func _unsafeUncheckedDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_internalInvariant(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inlinable
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<SwiftShims.HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
/// Get the minimum alignment for manually allocated memory.
///
/// Memory allocated via UnsafeMutable[Raw][Buffer]Pointer must never pass
/// an alignment less than this value to Builtin.allocRaw. This
/// ensures that the memory can be deallocated without specifying the
/// alignment.
@inlinable
@inline(__always)
internal func _minAllocationAlignment() -> Int {
return _swift_MinAllocationAlignment
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(x._value, true._value))
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(x._value, false._value))
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
// Optimizer hint that the condition is true. The condition is unchecked.
// The builtin acts as an opaque instruction with side-effects.
@usableFromInline @_transparent
func _uncheckedUnsafeAssume(_ condition: Bool) {
_ = Builtin.assume_Int1(condition._value)
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@usableFromInline
@_silgen_name("_swift_objcClassUsesNativeSwiftReferenceCounting")
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
/// Returns the class of a non-tagged-pointer Objective-C object
@_effects(readonly)
@_silgen_name("_swift_classOfObjCHeapObject")
internal func _swift_classOfObjCHeapObject(_ object: AnyObject) -> AnyClass
#else
@inlinable
@inline(__always)
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@usableFromInline
@_silgen_name("_swift_getSwiftClassInstanceExtents")
internal func getSwiftClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@usableFromInline
@_silgen_name("_swift_getObjCClassInstanceExtents")
internal func getObjCClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@inlinable
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(getObjCClassInstanceExtents(theClass).positive)
#else
return Int(getSwiftClassInstanceExtents(theClass).positive)
#endif
}
#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED
@usableFromInline
@_silgen_name("_swift_isImmutableCOWBuffer")
internal func _swift_isImmutableCOWBuffer(_ object: AnyObject) -> Bool
@usableFromInline
@_silgen_name("_swift_setImmutableCOWBuffer")
internal func _swift_setImmutableCOWBuffer(_ object: AnyObject, _ immutable: Bool) -> Bool
#endif
@inlinable
internal func _isValidAddress(_ address: UInt) -> Bool {
// TODO: define (and use) ABI max valid pointer value
return address >= _swift_abi_LeastValidPointerValue
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
// TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor
// calls
@inlinable
internal var _bridgeObjectTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) }
}
@inlinable
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_abi_ObjCReservedBitsMask) }
}
@inlinable
internal var _objectPointerSpareBits: UInt {
@inline(__always) get {
return UInt(_swift_abi_SwiftSpareBitsMask) & ~_bridgeObjectTaggedPointerBits
}
}
@inlinable
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get {
_internalInvariant(_swift_abi_ObjCReservedLowBits < 2,
"num bits now differs from num-shift-amount, new platform?")
return UInt(_swift_abi_ObjCReservedLowBits)
}
}
#if arch(i386) || arch(arm) || arch(wasm32) || arch(powerpc64) || arch(
powerpc64le) || arch(s390x) || arch(arm64_32)
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
#else
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
#endif
/// Extract the raw bits of `x`.
@inlinable
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@inlinable
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: UInt) -> Bool {
return (x & _objCTaggedPointerBits) != 0
}
/// TODO: describe extras
@inlinable @inline(__always) public // FIXME
func _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool {
return _bitPattern(x) & _bridgeObjectTaggedPointerBits != 0
}
@inlinable @inline(__always) public // FIXME
func _isNativePointer(_ x: Builtin.BridgeObject) -> Bool {
return (
_bitPattern(x) & (_bridgeObjectTaggedPointerBits | _objectPointerIsObjCBit)
) == 0
}
@inlinable @inline(__always) public // FIXME
func _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool {
return !_isTaggedObject(x) && !_isNativePointer(x)
}
@inlinable
@inline(__always)
func _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt {
// Zero out the tag bits, and leave them all at the top.
_internalInvariant(_isTaggedObject(x), "not tagged!")
return (_bitPattern(x) & ~_bridgeObjectTaggedPointerBits)
>> _objectPointerLowSpareBitShift
}
// Values -> BridgeObject
@inline(__always)
@inlinable
public func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let object = Builtin.castToBridgeObject(x, 0._builtinWordValue)
_internalInvariant(_isNativePointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNonTaggedObjC x: AnyObject
) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let object = _makeObjCBridgeObject(x)
_internalInvariant(_isNonTaggedObjCPointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject {
_internalInvariant(x & _bridgeObjectTaggedPointerBits != 0)
let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x._value)
_internalInvariant(_isTaggedObject(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject {
let shifted = x &<< _objectPointerLowSpareBitShift
_internalInvariant(x == (shifted &>> _objectPointerLowSpareBitShift),
"out-of-range: limited bit range requires some zero top bits")
_internalInvariant(shifted & _bridgeObjectTaggedPointerBits == 0,
"out-of-range: post-shift use of tag bits")
return _bridgeObject(fromTagged: shifted | _bridgeObjectTaggedPointerBits)
}
// BridgeObject -> Values
@inline(__always)
@inlinable
public func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject {
_internalInvariant(_isNativePointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
toNonTaggedObjC x: Builtin.BridgeObject
) -> AnyObject {
_internalInvariant(_isNonTaggedObjCPointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt {
_internalInvariant(_isTaggedObject(x))
let bits = _bitPattern(x)
_internalInvariant(bits & _bridgeObjectTaggedPointerBits != 0)
return bits
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt {
return _getNonTagBits(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNativeObject x: Builtin.NativeObject
) -> Builtin.BridgeObject {
return _bridgeObject(fromNative: _nativeObject(toNative: x))
}
//
// NativeObject
//
@inlinable
@inline(__always)
public func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let native = Builtin.unsafeCastToNativeObject(x)
// _internalInvariant(native == Builtin.castToNativeObject(x))
return native
}
@inlinable
@inline(__always)
public func _nativeObject(
fromBridge x: Builtin.BridgeObject
) -> Builtin.NativeObject {
return _nativeObject(fromNative: _bridgeObject(toNative: x))
}
@inlinable
@inline(__always)
public func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject {
return Builtin.castFromNativeObject(x)
}
// FIXME
extension ManagedBufferPointer {
// FIXME: String Guts
@inline(__always)
@inlinable
public init(_nativeObject buffer: Builtin.NativeObject) {
self._nativeBuffer = buffer
}
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@inlinable
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_internalInvariant(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inlinable
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@inlinable
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_internalInvariant(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_internalInvariant(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
public func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inlinable
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@usableFromInline @_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_internalInvariant(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_internalInvariant(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
@_alwaysEmitIntoClient
@_transparent
public // @testable
func _COWBufferForReading<T: AnyObject>(_ object: T) -> T {
return Builtin.COWBufferForReading(object)
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if `type` is known to refer to a concrete type once all
/// optimizations and constant folding has occurred at the call site. Otherwise,
/// this returns `false` if the check has failed.
///
/// Note that there may be cases in which, despite `T` being concrete at some
/// point in the caller chain, this function will return `false`.
@_alwaysEmitIntoClient
@_transparent
public // @testable
func _isConcrete<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isConcrete(type))
}
/// Returns `true` if type is a bitwise takable. A bitwise takable type can
/// just be moved to a different address in memory.
@_transparent
public // @testable
func _isBitwiseTakable<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isbitwisetakable(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
/// Extract an object reference from an Any known to contain an object.
@inlinable
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_internalInvariant(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// Ideally we would do something like this:
//
// func open<T>(object: T) -> AnyObject {
// return unsafeBitCast(object, to: AnyObject.self)
// }
// return _openExistential(any, do: open)
//
// Unfortunately, class constrained protocol existentials conform to AnyObject
// but are not word-sized. As a result, we cannot currently perform the
// `unsafeBitCast` on them just yet. When they are word-sized, it would be
// possible to efficiently grab the object reference out of the inline
// storage.
return any as AnyObject
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inlinable
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// can be a subtype of its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any` (the type
/// declared for the parameter) and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let t = type(of: value)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley: Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Finding the Dynamic Type in a Generic Context
/// =============================================
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function. As a result, `type(of:)` can only
/// produce the concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of `String.self` (the dynamic type inside the parameter).
///
/// func printGenericInfo<T>(_ value: T) {
/// let t = type(of: value)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let t = type(of: value as Any)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value for which to find the dynamic type.
/// - Returns: The dynamic type, which is a metatype instance.
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function;
/// nevertheless, it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve these errors, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed to `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameters:
/// - closure: A nonescaping closure value that is made escapable for the
/// duration of the execution of the `body` closure. If `body` has a
/// return value, that value is also used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - body: A closure that is executed immediately with an escapable copy of
/// `closure` as its argument.
/// - Returns: The return value, if any, of the `body` closure.
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Given a string that is constructed from a string literal, return a pointer
/// to the global string table location that contains the string literal.
/// This function will trap when it is invoked on strings that are not
/// constructed from literals or if the construction site of the string is not
/// in the function containing the call to this SPI.
@_transparent
@_alwaysEmitIntoClient
public // @SPI(OSLog)
func _getGlobalStringTablePointer(_ constant: String) -> UnsafePointer<CChar> {
return UnsafePointer<CChar>(Builtin.globalStringTablePointer(constant));
}
| 36.252725 | 95 | 0.708521 |
def48dad54c65b496025fc0494dd86c57246629b | 2,593 | //
// ChangeEmailViewController.swift
// Polling
//
// Created by Warakorn Rungseangthip on 11/10/2559 BE.
// Copyright © 2559 Warakorn Rungseangthip. All rights reserved.
//
import UIKit
import Firebase
class ChangeEmailViewController: UITableViewController {
@IBOutlet weak var txtChangeEmail: UITextField!
var loggedInUser = AnyObject?()
var databaseRef = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).observeSingleEventOfType(.Value) { (snapshot:FIRDataSnapshot) in
self.txtChangeEmail.text = snapshot.value!["email"] as? String
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveEmailAction(sender: AnyObject) {
if self.txtChangeEmail.text == ""
{
let alertController = UIAlertController(title: "", message: "Please enter Email", preferredStyle: .Alert)
let defaultActon = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(defaultActon)
self.presentViewController(alertController, animated: true, completion: nil)
}
else
{
let user = FIRAuth.auth()?.currentUser
user?.updateEmail(txtChangeEmail.text!) { error in
if error != nil {
let alertController = UIAlertController(title: "Oop!", message: (error?.localizedDescription)!, preferredStyle: .Alert)
let defaultActon = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(defaultActon)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).child("email").setValue(self.txtChangeEmail.text)
self.navigationController?.popViewControllerAnimated(true);
}
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
| 33.675325 | 141 | 0.603162 |
916b759254a85cb68dec0f9a4bcc3519d6b0d35e | 2,388 | //
// String.swift
// Pods
//
// Created by Ceferino Jose II on 10/10/18.
//
import Foundation
extension String {
/// Changes the current value (*mutating*) of the String by calling PowerUpSwift's `sanitize()`
public mutating func sanitized() {
self = self.sanitize()
}
/// Returns the trimmed valueof the String by:
/// - removing all the white spaces and white new lines around
/// - replacing two or more spaces inside with a single space
/// - replacing three or more new lines inside with two new lines
///
/// **It should just work! Trust PowerUpSwift. 😂😂😂**
public func sanitize() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "\\ \\ +", with: " ", options: .regularExpression)
.replacingOccurrences(of: "\n\n\n+", with: "\n\n", options: .regularExpression)
}
/// Checks if the String is a valid email and returns a Bool.
public var isValidEmail: Bool {
let regEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let predicate = NSPredicate(format:"SELF MATCHES %@", regEx)
return predicate.evaluate(with: self)
}
/// Reverses the value of `isValidEmail` so it feels more natural to write than using an exclamation point.
public var isNotValidEmail: Bool {
return !self.isValidEmail
}
/// Reverses the built-in `isEmpty` so it feels more natural to write than using an exclamation point.
public var isNotEmpty: Bool {
return !self.isEmpty
}
/// Uses the very `String` as the **key** to find the value from the Localizable resources and return the localized **value**.
public var localized: String {
return NSLocalizedString(self, comment: "")
}
func limitLength(_ n: Int) -> String {
if self.count <= n {
return self
}
return String(Array(self).prefix(upTo: n))
}
}
// MARK: - Deprecated
extension String {
// This is how we are going to deprecate things.
// @available(*, deprecated, renamed: "sanitize", message: "This is effective starting in version x.x.x.")
// @available(*, unavailable, renamed: "sanitize", message: "This will no longer work starting in version x.x.x.")
// public func oldFunction() {
// self.newFunction()
// }
}
| 35.641791 | 130 | 0.626466 |
1e63133c3c156988dde850562da91b1db56492a0 | 4,413 | // Generated by Lona Compiler 0.5.3
import AppKit
import Foundation
// MARK: - TextStylePreviewCollection
public class TextStylePreviewCollection: NSBox {
// MARK: Lifecycle
public init(_ parameters: Parameters) {
self.parameters = parameters
super.init(frame: .zero)
setUpViews()
setUpConstraints()
update()
}
public convenience init(textStyles: TextStyleList) {
self.init(Parameters(textStyles: textStyles))
}
public convenience init() {
self.init(Parameters())
}
public required init?(coder aDecoder: NSCoder) {
self.parameters = Parameters()
super.init(coder: aDecoder)
setUpViews()
setUpConstraints()
update()
}
// MARK: Public
public var onSelectTextStyle: TextStyleHandler {
get { return parameters.onSelectTextStyle }
set { parameters.onSelectTextStyle = newValue }
}
public var onChangeTextStyle: TextStyleHandler {
get { return parameters.onChangeTextStyle }
set { parameters.onChangeTextStyle = newValue }
}
public var onDeleteTextStyle: TextStyleHandler {
get { return parameters.onDeleteTextStyle }
set { parameters.onDeleteTextStyle = newValue }
}
public var onMoveTextStyle: ItemMoveHandler {
get { return parameters.onMoveTextStyle }
set { parameters.onMoveTextStyle = newValue }
}
public var textStyles: TextStyleList {
get { return parameters.textStyles }
set {
if parameters.textStyles != newValue {
parameters.textStyles = newValue
}
}
}
public var parameters: Parameters {
didSet {
if parameters != oldValue {
update()
}
}
}
// MARK: Private
private func setUpViews() {
boxType = .custom
borderType = .noBorder
contentViewMargins = .zero
fillColor = Colors.pink50
}
private func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
}
private func update() {}
private func handleOnSelectTextStyle(_ arg0: CSTextStyle?) {
onSelectTextStyle?(arg0)
}
private func handleOnChangeTextStyle(_ arg0: CSTextStyle?) {
onChangeTextStyle?(arg0)
}
private func handleOnDeleteTextStyle(_ arg0: CSTextStyle?) {
onDeleteTextStyle?(arg0)
}
private func handleOnMoveTextStyle(_ arg0: Int, _ arg1: Int) {
onMoveTextStyle?(arg0, arg1)
}
}
// MARK: - Parameters
extension TextStylePreviewCollection {
public struct Parameters: Equatable {
public var textStyles: TextStyleList
public var onSelectTextStyle: TextStyleHandler
public var onChangeTextStyle: TextStyleHandler
public var onDeleteTextStyle: TextStyleHandler
public var onMoveTextStyle: ItemMoveHandler
public init(
textStyles: TextStyleList,
onSelectTextStyle: TextStyleHandler = nil,
onChangeTextStyle: TextStyleHandler = nil,
onDeleteTextStyle: TextStyleHandler = nil,
onMoveTextStyle: ItemMoveHandler = nil)
{
self.textStyles = textStyles
self.onSelectTextStyle = onSelectTextStyle
self.onChangeTextStyle = onChangeTextStyle
self.onDeleteTextStyle = onDeleteTextStyle
self.onMoveTextStyle = onMoveTextStyle
}
public init() {
self.init(textStyles: [])
}
public static func ==(lhs: Parameters, rhs: Parameters) -> Bool {
return lhs.textStyles == rhs.textStyles
}
}
}
// MARK: - Model
extension TextStylePreviewCollection {
public struct Model: LonaViewModel, Equatable {
public var id: String?
public var parameters: Parameters
public var type: String {
return "TextStylePreviewCollection"
}
public init(id: String? = nil, parameters: Parameters) {
self.id = id
self.parameters = parameters
}
public init(_ parameters: Parameters) {
self.parameters = parameters
}
public init(
textStyles: TextStyleList,
onSelectTextStyle: TextStyleHandler = nil,
onChangeTextStyle: TextStyleHandler = nil,
onDeleteTextStyle: TextStyleHandler = nil,
onMoveTextStyle: ItemMoveHandler = nil)
{
self
.init(
Parameters(
textStyles: textStyles,
onSelectTextStyle: onSelectTextStyle,
onChangeTextStyle: onChangeTextStyle,
onDeleteTextStyle: onDeleteTextStyle,
onMoveTextStyle: onMoveTextStyle))
}
public init() {
self.init(textStyles: [])
}
}
}
| 23.349206 | 69 | 0.684342 |
9bb145b15ec384f6e8df16ce59ddce8000c75536 | 828 | //
// NotificationUsageUITestsLaunchTests.swift
// NotificationUsageUITests
//
// Created by cemal tüysüz on 1.01.2022.
//
import XCTest
class NotificationUsageUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 25.090909 | 88 | 0.684783 |
ffbf48acc773b61ba13c8261268ee9935c2bd3bf | 2,602 | import GameKit
public class GameCenter: NSObject, GKGameCenterControllerDelegate {
public static let shared: GameCenter = GameCenter()
private weak var presentingViewController: UIViewController!
public func authenticateLocalUser() {
print("Authenticating local user...")
if GKLocalPlayer.local.isAuthenticated == false {
GKLocalPlayer.local.authenticateHandler = { (view, error) in
guard error == nil else {
print("Authentication error: \(String(describing: error?.localizedDescription))")
return
}
}
} else {
print("Already authenticated")
}
}
public func reportAchievementIdentifier(_ identifier: String, percent: Double, showsCompletionBanner banner: Bool = true) {
let achievement = GKAchievement(identifier: identifier)
achievement.percentComplete = percent
achievement.showsCompletionBanner = banner
GKAchievement.report([achievement]) { (error) in
guard error == nil else {
print("Error in reporting achievements: \(String(describing: error))")
return
}
}
}
public func resetAllAchievements() {
GKAchievement.resetAchievements { (error) in
guard error == nil else {
print("Error resetting achievements: \(String(describing: error))")
return
}
}
}
public func reportLeaderboardIdentifier(_ identifier: String, score: Int) {
let scoreObject = GKScore(leaderboardIdentifier: identifier)
scoreObject.value = Int64(score)
GKScore.report([scoreObject]) { (error) in
guard error == nil else {
print("Error in reporting leaderboard scores: \(String(describing: error))")
return
}
}
}
public func showGameCenter(_ viewController: UIViewController, viewState: GKGameCenterViewControllerState) {
presentingViewController = viewController
let gcvc = GKGameCenterViewController()
gcvc.viewState = viewState
gcvc.gameCenterDelegate = self
presentingViewController.present(gcvc, animated: true, completion: nil)
}
// MARK: GKGameCenterControllerDelegate
public func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
presentingViewController.dismiss(animated: true, completion: nil)
}
}
| 36.138889 | 127 | 0.621829 |
5d8c5afbdba0bec9ad78d731d95f3d978375fe68 | 15,313 | // ----------------------------------------------------------------------------
//
// IntegerOperatorsTests.SignedIntegers.swift
//
// @author Natalia Mamunina <[email protected]>
// @copyright Copyright (c) 2018, Roxie Mobile Ltd. All rights reserved.
// @link http://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
@testable import SwiftCommonsData
import XCTest
// ----------------------------------------------------------------------------
// MARK: - Signed Integers
// ----------------------------------------------------------------------------
extension IntegerOperatorsTests
{
// MARK: - Tests
func testSignedIntegers_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.integerValues)
// --
let _int8Value: Int8 = 0
// Positive
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertEqual(i8v, Int8.max)
}
// Negative
assertThrowsException {
var i8v = _int8Value
i8v <~ map[JsonKeys.noSuchKey]
}
assertThrowsException {
var i8v = _int8Value
i8v <~ map[JsonKeys.invalidValue]
}
assertThrowsException {
var i8v = _int8Value
i8v <~ map[JsonKeys.nilValue]
}
// --
let _int16Value: Int16 = 0
// Positive
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertEqual(i16v, Int16.max)
}
// Negative
assertThrowsException {
var i16v = _int16Value
i16v <~ map[JsonKeys.noSuchKey]
}
assertThrowsException {
var i16v = _int16Value
i16v <~ map[JsonKeys.invalidValue]
}
assertThrowsException {
var i16v = _int16Value
i16v <~ map[JsonKeys.nilValue]
}
// --
let _int32Value: Int32 = 0
// Positive
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertEqual(i32v, Int32.max)
}
// Negative
assertThrowsException {
var i32v = _int32Value
i32v <~ map[JsonKeys.noSuchKey]
}
assertThrowsException {
var i32v = _int32Value
i32v <~ map[JsonKeys.invalidValue]
}
assertThrowsException {
var i32v = _int32Value
i32v <~ map[JsonKeys.nilValue]
}
// --
let _int64Value: Int64 = 0
// Positive
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertEqual(i64v, Int64.max)
}
// Negative
assertThrowsException {
var i64v = _int64Value
i64v <~ map[JsonKeys.noSuchKey]
}
assertThrowsException {
var i64v = _int64Value
i64v <~ map[JsonKeys.invalidValue]
}
assertThrowsException {
var i64v = _int64Value
i64v <~ map[JsonKeys.nilValue]
}
// --
let _intValue: Int = 0
// Positive
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.int]
XCTAssertEqual(ival, Int.max)
}
// Negative
assertThrowsException {
var ival = _intValue
ival <~ map[JsonKeys.noSuchKey]
}
assertThrowsException {
var ival = _intValue
ival <~ map[JsonKeys.invalidValue]
}
assertThrowsException {
var ival = _intValue
ival <~ map[JsonKeys.nilValue]
}
}
func testSignedIntegers_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _int8Value = Int8.max
let _int16Value = Int16.max
let _int32Value = Int32.max
let _int64Value = Int64.max
let _intValue = Int.max
// Positive
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int8).value)
}
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int16).value)
}
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int32).value)
}
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int64).value)
}
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.int]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int).value)
}
}
}
// ----------------------------------------------------------------------------
// MARK: - Optional signed Integers
// ----------------------------------------------------------------------------
extension IntegerOperatorsTests
{
// MARK: - Tests
func testOptionalSignedIntegers_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.integerValues)
// --
let _int8Value: Int8? = nil
// Positive
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertEqual(i8v, Int8.max)
}
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i8v)
}
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.nilValue]
XCTAssertNil(i8v)
}
// Negative
assertThrowsException {
var i8v = _int8Value
i8v <~ map[JsonKeys.invalidValue]
}
// --
let _int16Value: Int16? = nil
// Positive
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertEqual(i16v, Int16.max)
}
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i16v)
}
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.nilValue]
XCTAssertNil(i16v)
}
// Negative
assertThrowsException {
var i16v = _int16Value
i16v <~ map[JsonKeys.invalidValue]
}
// --
let _int32Value: Int32? = nil
// Positive
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertEqual(i32v, Int32.max)
}
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i32v)
}
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.nilValue]
XCTAssertNil(i32v)
}
// Negative
assertThrowsException {
var i32v = _int32Value
i32v <~ map[JsonKeys.invalidValue]
}
// --
let _int64Value: Int64? = nil
// Positive
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertEqual(i64v, Int64.max)
}
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i64v)
}
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.nilValue]
XCTAssertNil(i64v)
}
// Negative
assertThrowsException {
var i64v = _int64Value
i64v <~ map[JsonKeys.invalidValue]
}
// --
let _intValue: Int? = nil
// Positive
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.int]
XCTAssertEqual(ival, Int.max)
}
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.noSuchKey]
XCTAssertNil(ival)
}
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.nilValue]
XCTAssertNil(ival)
}
// Negative
assertThrowsException {
var ival = _intValue
ival <~ map[JsonKeys.invalidValue]
}
}
func testOptionalSignedIntegers_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _int8Value: Int8? = Int8.max
let _int16Value: Int16? = Int16.max
let _int32Value: Int32? = Int32.max
let _int64Value: Int64? = Int64.max
let _intValue: Int? = Int.max
let _nilValue: Int? = nil
// Positive
assertNoThrow {
var i8v = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int8).value)
}
assertNoThrow {
var i16v = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int16).value)
}
assertNoThrow {
var i32v = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int32).value)
}
assertNoThrow {
var i64v = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int64).value)
}
assertNoThrow {
var ival = _intValue
ival <~ map[JsonKeys.int]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int).value)
}
assertNoThrow {
var ival = _nilValue
ival <~ map[JsonKeys.nilValue]
XCTAssertNil(map.fetch(valueFor: JsonKeys.nilValue).value)
}
}
}
// ----------------------------------------------------------------------------
// MARK: - Implicitly unwrapped optional signed Integers
// ----------------------------------------------------------------------------
extension IntegerOperatorsTests
{
// MARK: - Tests
func testImplicitlyUnwrappedOptionalSignedIntegers_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.integerValues)
// --
let _int8Value: Int8! = 0
// Positive
assertNoThrow {
var i8v: Int8! = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertEqual(i8v, Int8.max)
}
assertNoThrow {
var i8v: Int8! = _int8Value
i8v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i8v)
}
assertNoThrow {
var i8v: Int8! = _int8Value
i8v <~ map[JsonKeys.nilValue]
XCTAssertNil(i8v)
}
// Negative
assertThrowsException {
var i8v: Int8! = _int8Value
i8v <~ map[JsonKeys.invalidValue]
}
// --
let _int16Value: Int16! = 0
// Positive
assertNoThrow {
var i16v: Int16! = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertEqual(i16v, Int16.max)
}
assertNoThrow {
var i16v: Int16! = _int16Value
i16v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i16v)
}
assertNoThrow {
var i16v: Int16! = _int16Value
i16v <~ map[JsonKeys.nilValue]
XCTAssertNil(i16v)
}
// Negative
assertThrowsException {
var i16v: Int16! = _int16Value
i16v <~ map[JsonKeys.invalidValue]
}
// --
let _int32Value: Int32! = 0
// Positive
assertNoThrow {
var i32v: Int32! = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertEqual(i32v, Int32.max)
}
assertNoThrow {
var i32v: Int32! = _int32Value
i32v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i32v)
}
assertNoThrow {
var i32v: Int32! = _int32Value
i32v <~ map[JsonKeys.nilValue]
XCTAssertNil(i32v)
}
// Negative
assertThrowsException {
var i32v: Int32! = _int32Value
i32v <~ map[JsonKeys.invalidValue]
}
// --
let _int64Value: Int64! = 0
// Positive
assertNoThrow {
var i64v: Int64! = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertEqual(i64v, Int64.max)
}
assertNoThrow {
var i64v: Int64! = _int64Value
i64v <~ map[JsonKeys.noSuchKey]
XCTAssertNil(i64v)
}
assertNoThrow {
var i64v: Int64! = _int64Value
i64v <~ map[JsonKeys.nilValue]
XCTAssertNil(i64v)
}
// Negative
assertThrowsException {
var i64v: Int64! = _int64Value
i64v <~ map[JsonKeys.invalidValue]
}
// --
let _intValue: Int! = 0
// Positive
assertNoThrow {
var ival: Int! = _intValue
ival <~ map[JsonKeys.int]
XCTAssertEqual(ival, Int.max)
}
assertNoThrow {
var ival: Int! = _intValue
ival <~ map[JsonKeys.noSuchKey]
XCTAssertNil(ival)
}
assertNoThrow {
var ival: Int! = _intValue
ival <~ map[JsonKeys.nilValue]
XCTAssertNil(ival)
}
// Negative
assertThrowsException {
var ival: Int! = _intValue
ival <~ map[JsonKeys.invalidValue]
}
}
func testImplicitlyUnwrappedOptionalSignedIntegers_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _int8Value: Int8! = Int8.max
let _int16Value: Int16! = Int16.max
let _int32Value: Int32! = Int32.max
let _int64Value: Int64! = Int64.max
let _intValue: Int! = Int.max
// Positive
assertNoThrow {
var i8v: Int8! = _int8Value
i8v <~ map[JsonKeys.int8]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int8).value)
}
assertNoThrow {
var i16v: Int16! = _int16Value
i16v <~ map[JsonKeys.int16]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int16).value)
}
assertNoThrow {
var i32v: Int32! = _int32Value
i32v <~ map[JsonKeys.int32]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int32).value)
}
assertNoThrow {
var i64v: Int64! = _int64Value
i64v <~ map[JsonKeys.int64]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int64).value)
}
assertNoThrow {
var ival: Int! = _intValue
ival <~ map[JsonKeys.int]
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.int).value)
}
}
}
// ----------------------------------------------------------------------------
| 26.770979 | 79 | 0.497159 |
3ab052d16728ea5eef954d3fb26285002d04c25a | 1,033 | //
// Navigator.swift
// macOS
//
// Created by Lucka on 20/10/2021.
//
import SwiftUI
class Navigator: ObservableObject {
#if os(macOS)
enum Tag: Hashable {
case dashboard
case list
case map
}
#endif
struct Configuration {
let title: LocalizedStringKey
let predicate: NSPredicate?
init(
_ title: LocalizedStringKey = "view.dashboard.highlights.all",
predicate: NSPredicate? = nil
) {
self.title = title
self.predicate = predicate
}
}
#if os(macOS)
@Published var actived: Tag? = .dashboard
@Published var configuration: Configuration = .init()
#else
@Published var selection: Nomination? = nil
#endif
#if os(macOS)
func open(_ panel: Tag, with configuration: Configuration?) {
if let solidConfiguration = configuration {
self.configuration = solidConfiguration
}
actived = panel
}
#endif
}
| 21.081633 | 74 | 0.574056 |
e813fc2b5f3ac230e54e25095734ddff9b1e974a | 269 | //
// AppDelegate.swift
// Detecting Which Floor the User Is on in a Building
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 14.157895 | 55 | 0.713755 |
56f7a6c2a34a5ad414c794dc12bc9a35e41b3491 | 2,015 | // Created by Gil Birman on 1/11/20.
import Combine
import Foundation
/// Similar to a thunk, except that it will retain a `Set` of
/// `AnyCancellable` instances while your Combine pipelines process an async task.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public final class PublisherAction<State>: Action {
// MARK: Public
public typealias GetState = () -> State?
public typealias Cancellables = Set<AnyCancellable>
public typealias Body = (
_ dispatch: @escaping Dispatch,
_ getState: @escaping GetState,
_ cancellables: inout Cancellables)
-> Void
/// Instantiates an async action that retains Combine cancel objects.
///
/// PublisherAction<MyState> { dispatch, getState, cancellables in
/// myPublisher1
/// ...
/// .tap { ... }
/// .store(in: &cancellables)
/// myPublisher2
/// ...
/// .tap { ... }
/// .store(in: &cancellables)
/// ...
/// }
///
/// `body` function arguments:
/// - `dispatch`: Dispatch an action.
/// - `getState`: Get state of the store.
/// - `cancellables`: Set of cancellables retained by this PublisherAction instance.
///
/// - Parameter description: Description of this action for debugging/logging
/// - Parameter body: Function that is executed when this action is dispatched.
public init(description: String? = nil, body: @escaping Body) {
debugDescription = description
self.body = body
}
// MARK: Internal
func execute(
dispatch: @escaping Dispatch,
getState: @escaping GetState)
{
body(dispatch, getState, &cancellables)
}
// MARK: Private
private let debugDescription: String?
private let body: Body!
private var cancellables = Cancellables()
}
extension PublisherAction: CustomStringConvertible {
public var description: String {
"[PublisherAction<\(type(of: State.self))>] \(debugDescription ?? "") (\(cancellables.count) cancellables)"
}
}
| 29.632353 | 111 | 0.642184 |
89403760429ec66cac7872472a879622365d100a | 1,669 | /*
-----------------------------------------------------------------------------
This source file is part of MedKitMIP.
Copyright 2017-2018 Jon Griffeth
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-----------------------------------------------------------------------------
*/
import Foundation
import MedKitCore
class MIPV1ResourceNotify: MIPV1ResourceNotification {
// MARK: - Properties
var type : MIPV1ResourceNotificationType { return .notify }
let args : AnyCodable
// MARK: - Initializers
init(_ args: AnyCodable)
{
self.args = args
}
// MARK: - Codable
required init(from decoder: Decoder) throws
{
let container = try decoder.singleValueContainer()
args = try container.decode(AnyCodable.self)
}
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: MIPV1MethodCodingKeys.self)
try container.encode(type, forKey: .method)
try container.encode(args, forKey: .args)
}
func send(to client: MIPV1Client, from resource: ResourceBackend)
{
client.resource(resource, didNotify: args)
}
}
// End of File
| 25.676923 | 78 | 0.636908 |
f8cb75d13f63261a793b160e401be5bfc4c8ceb3 | 135 | //
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import Foundation
enum UnitType: String, Codable {
case kg
case mm
}
| 12.272727 | 55 | 0.696296 |
2968ce70757f62c7d4cb15b9ce020fec31690f51 | 608 | //
// FNSLaMuseModel.swift
// Awesome ML
//
// Created by Eugene Bokhan on 4/6/18.
// Copyright © 2018 Eugene Bokhan. All rights reserved.
//
import Foundation
public let fnsLaMuseModel = CoreMLModel(name: "FNS-LaMuse", machineLearningModelType: .fnsLaMuse, shortDescription: "Feedforward style transfer", detailedDescriptionURL: Bundle.main.url(forResource: "FNS", withExtension: "md")!, coverImage: #imageLiteral(resourceName: "FNS-LaMuse Cover"), inputWidth: 720, inputHeight: 720, remoteURL: URL(string: "https://s3-us-west-2.amazonaws.com/coreml-models/FNS-La-Muse.mlmodel")!, remoteZipURL: nil)
| 46.769231 | 440 | 0.754934 |
e55d790518a238f97aef9b5b104bfa4af12502af | 13,751 | //
// User.swift
// YumFun
//
// Created by Yibo Yan on 2021/2/22.
//
import Foundation
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift
final class User: Identifiable, Codable {
/// This id maps to the uid created by Firebase authentication
@DocumentID var id: String?
/// This is used to track last update date
@ServerTimestamp var lastUpdated: Timestamp?
var displayName: String?
var userName: String?
var email: String?
var photoUrl: String?
var bio: String?
fileprivate(set) var recipes: [String] = [] {
willSet {
if let validId = self.id {
User.update(named: validId, with: ["recipes": newValue]) { (err) in
if let err = err {
print("Failed to update recipes in user. \(err)")
}
}
}
}
}
fileprivate(set) var followers = [String]()
fileprivate(set) var followings: [String] = [] {
willSet {
if let validId = self.id {
User.update(named: validId, with: ["followings": newValue]) { (err) in
if let err = err {
print("Failed to update followings in user. \(err)")
}
}
}
}
}
private(set) var likedRecipes: [String] = [] {
willSet {
if let validId = self.id {
User.update(named: validId, with: ["likedRecipes": newValue]) { (err) in
if let err = err {
print("Failed to update liked recipes in user. \(err)")
}
}
}
}
}
init() {
// zero initialization
}
init(fromAuthUser authUser: Firebase.User) {
self.id = authUser.uid
self.displayName = authUser.displayName
self.email = authUser.email
}
}
extension User: CrudOperable {
static var collectionPath: String {
"user"
}
}
extension User {
typealias createUserCompletionHandler = ((AuthDataResult?, Error?) -> Void)
/**
Wrap function for firebase `createUser` function.
## Note
Do not directly use firebase's `createUser` functino. Instead, use this function to create user. It will post user data to the firestore at the same time when creating a user in the firebase.
*/
static func createUser(withEmail email: String,
withPassword password: String,
completion: @escaping createUserCompletionHandler) {
FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password) { result, error in
guard error == nil else {
completion(result, error)
return
}
if let user = result?.user {
let newUser = User(fromAuthUser: user)
User.post(with: newUser, named: user.uid) { (err, _) in
completion(result, err)
}
} else {
completion(result, CoreError.currUserNoDataError)
}
}
}
}
/// Basic operations for current user. For example, create a recipe, update their profile image, etc.
extension User {
/**
Create recipe. This function should only be used to create a recipe for __current user__.
*/
func createRecipe(with recipe: Recipe, _ completion: @escaping postDataCompletionHandler) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError, nil)
return
}
var recipe = recipe
recipe.author = currUserId
Recipe.post(with: recipe) { (err, docRef) in
if let err = err {
completion(err, docRef)
} else {
if let docId = docRef?.documentID {
self.recipes.append(docId)
}
completion(nil, docRef)
}
}
}
/**
Delete recipe by specified recipe id.
*/
func deleteRecipe(withId recipeId: String,
_ completion: @escaping updateDataCompletionHandler) {
guard self.id != nil else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
self.recipes.removeAll { $0 == recipeId }
Recipe.delete(named: recipeId) { (error) in
completion(error)
}
}
/**
Current user follows other user with specified user id.
*/
func followUser(withId userId: String,
_ completion: @escaping updateDataCompletionHandler) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
self.followings.append(userId)
let newData = ["followers" : FieldValue.arrayUnion([currUserId])]
User.update(named: userId, with: newData, completion)
}
/**
Current user unfollows other user with specified user id.
*/
func unfollowUser(withId userId: String,
_ completion: @escaping updateDataCompletionHandler) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
self.followings.removeAll { $0 == userId }
let newData = ["followers" : FieldValue.arrayRemove([currUserId])]
User.update(named: userId, with: newData, completion)
}
/**
Current user liked a recipe.
*/
func likeRecipe(withId id: String,
_ completion: @escaping updateDataCompletionHandler) {
guard self.id != nil else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
self.likedRecipes.append(id)
let newData = [
"likedCount": FieldValue.increment(Int64(1))
]
Recipe.update(named: id, with: newData, completion)
}
/**
Current user unliked a recipe.
*/
func unlikeRecipe(withId id: String,
_ completion: @escaping updateDataCompletionHandler) {
guard self.id != nil else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
self.likedRecipes.removeAll { $0 == id }
let newData = [
"likedCount": FieldValue.increment(Int64(-1))
]
Recipe.update(named: id, with: newData, completion)
}
/**
Current user upload a profile image to the server
*/
func updateProfileImage(with image: UIImage,
_ completion: @escaping (Error?, CloudStorage?) -> Void) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError, nil)
return
}
let image = image.wxCompress()
let data = image.jpegData(compressionQuality: 0.5)
guard let validData = data else {
completion(CoreError.failedCompressImageError, nil)
return
}
let storage = CloudStorage(.profileImage)
storage.child("\(currUserId).jpeg")
storage.upload(validData, metadata: nil) { (error) in
completion(error, nil)
} completionHandler: { metadata in
self.photoUrl = storage.fileRef.fullPath
let newData = ["photoUrl": storage.fileRef.fullPath]
User.update(named: currUserId, with: newData) { (error) in
completion(error, storage)
}
}
}
/**
Update current user's display name.
*/
func updateDisplayName(withNewName name: String,
_ completion: @escaping updateDataCompletionHandler) {
self.displayName = name
self.updateUserStrField(withFieldName: "displayName", withFieldValue: name, completion)
}
/**
Update current user's user name.
*/
func updateUsername(withNewName name: String,
_ completion: @escaping updateDataCompletionHandler) {
self.userName = name
self.updateUserStrField(withFieldName: "userName", withFieldValue: name, completion)
}
/**
Update current user's bio.
*/
func updateBio(withNewBio bio: String,
_ completion: @escaping updateDataCompletionHandler) {
self.bio = bio
self.updateUserStrField(withFieldName: "bio", withFieldValue: bio, completion)
}
}
extension User {
/**
Create a collab cooking session from current user with a __recipe id__. This action will set current user as the host automatically.
__Newly created collab cook session id will be passed back as the second argument in the completion handler.__
- Parameter recipeId: recipe id which collab cook session based on
- Parameter completion: The first argument passed back is the Error, if any. The second argument passed back is the newly created session number.
*/
func createCollabSession(withRecipeId recipeId: String,
_ completion: @escaping (Error?, String?) -> Void) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError, nil)
return
}
CollabSession.createSession(withHostId: currUserId, withRecipeId: recipeId, completion)
}
/**
Create a collab cooking session from current user with a __recipe__. This action will set current user as the host automatically.
__Newly created collab cook session id will be passed back as the second argument in the completion handler.__
- Parameter recipeId: recipe id which collab cook session based on
- Parameter completion: The first argument passed back is the Error, if any. The second argument passed back is the newly created session number.
*/
func createCollabSession(withRecipe recipe: Recipe,
_ completion: @escaping (Error?, String?) -> Void) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError, nil)
return
}
CollabSession.createSession(withHostId: currUserId, withRecipe: recipe, completion)
}
/**
Join a collab session for current user.
## Note
As a host, you need to call `createCollabSession` first to get the newly created session id. And join session with that id.
This function will return a `Listener` if executed successfully. If possible, you should always pass this listener back to the `leaveCollabSession` function to clean up, if you intend to leave.
- Parameter sessionId: the session id you want to join
- Parameter completion: a completion handler to indicate whether there is a error.
- Parameter changedHandler: this is important, as it will keep you data sync with cloud real-time. This handler will be called everytime when the cloud data update is detected. The new data will be passed into this handler as an argument.
*/
func joinCollabSession(withSessionId sessionId: String,
completion: @escaping (Error?) -> Void,
whenChanged changedHandler: @escaping (CollabSession) -> Void) -> ListenerRegistration? {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return nil
}
return CollabSession.joinSession(withSessionId: sessionId, withParticipantId: currUserId, completion: completion, whenChanged: changedHandler)
}
/**
Leave the specified collab session for current user.
## Note
If possible, always execute this function before you leave the collab session or navigate to other views. Remove listener is important to avoid latent crash.
*/
func leaveCollabSession(withSessionId sessionId: String,
withListener listener: ListenerRegistration,
completion: @escaping (Error?) -> Void) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
CollabSession.leaveSession(withSessionId: sessionId, withParticipantId: currUserId, withListener: listener, completion: completion)
}
}
extension User {
private func updateUserStrField(withFieldName fieldName: String,
withFieldValue fieldValue: Any,
_ completion: @escaping updateDataCompletionHandler) {
guard let currUserId = self.id else {
print("Failed to fetch current user id")
completion(CoreError.currUserNoDataError)
return
}
let newData = [fieldName: fieldValue]
User.update(named: currUserId, with: newData, completion)
}
}
| 35.809896 | 243 | 0.589921 |
76a4022158477729f126876badc60eaf39367ced | 5,080 | //
// Created by Anton Heestand on 2022-01-07.
//
import Foundation
import CoreGraphics
import RenderKit
import Resolution
import PixelColor
public struct LumaLevelsPixelModel: PixelMergerEffectModel {
// MARK: Global
public var id: UUID = UUID()
public var name: String = "Luma Levels"
public var typeName: String = "pix-effect-merger-luma-levels"
public var bypass: Bool = false
public var inputNodeReferences: [NodeReference] = []
public var outputNodeReferences: [NodeReference] = []
public var viewInterpolation: ViewInterpolation = .linear
public var interpolation: PixelInterpolation = .linear
public var extend: ExtendMode = .zero
public var placement: Placement = .fit
// MARK: Local
public var brightness: CGFloat = 1.0
public var darkness: CGFloat = 0.0
public var contrast: CGFloat = 0.0
public var gamma: CGFloat = 1.0
public var inverted: Bool = false
public var smooth: Bool = false
public var opacity: CGFloat = 1.0
public var offset: CGFloat = 0.0
public var lumaGamma: CGFloat = 1.0
}
extension LumaLevelsPixelModel {
enum LocalCodingKeys: String, CodingKey, CaseIterable {
case brightness
case darkness
case contrast
case gamma
case inverted
case smooth
case opacity
case offset
case lumaGamma
}
public init(from decoder: Decoder) throws {
self = try PixelMergerEffectModelDecoder.decode(from: decoder, model: self) as! Self
let container = try decoder.container(keyedBy: LocalCodingKeys.self)
if try PixelModelDecoder.isLiveListCodable(decoder: decoder) {
let liveList: [LiveWrap] = try PixelModelDecoder.liveListDecode(from: decoder)
for codingKey in LocalCodingKeys.allCases {
guard let liveWrap: LiveWrap = liveList.first(where: { $0.typeName == codingKey.rawValue }) else { continue }
switch codingKey {
case .brightness:
guard let live = liveWrap as? LiveFloat else { continue }
brightness = live.wrappedValue
case .darkness:
guard let live = liveWrap as? LiveFloat else { continue }
darkness = live.wrappedValue
case .contrast:
guard let live = liveWrap as? LiveFloat else { continue }
contrast = live.wrappedValue
case .gamma:
guard let live = liveWrap as? LiveFloat else { continue }
gamma = live.wrappedValue
case .inverted:
guard let live = liveWrap as? LiveBool else { continue }
inverted = live.wrappedValue
case .smooth:
guard let live = liveWrap as? LiveBool else { continue }
smooth = live.wrappedValue
case .opacity:
guard let live = liveWrap as? LiveFloat else { continue }
opacity = live.wrappedValue
case .offset:
guard let live = liveWrap as? LiveFloat else { continue }
offset = live.wrappedValue
case .lumaGamma:
guard let live = liveWrap as? LiveFloat else { continue }
lumaGamma = live.wrappedValue
}
}
return
}
brightness = try container.decode(CGFloat.self, forKey: .brightness)
darkness = try container.decode(CGFloat.self, forKey: .darkness)
contrast = try container.decode(CGFloat.self, forKey: .contrast)
gamma = try container.decode(CGFloat.self, forKey: .gamma)
inverted = try container.decode(Bool.self, forKey: .inverted)
smooth = try container.decode(Bool.self, forKey: .smooth)
opacity = try container.decode(CGFloat.self, forKey: .opacity)
offset = try container.decode(CGFloat.self, forKey: .offset)
lumaGamma = try container.decode(CGFloat.self, forKey: .lumaGamma)
}
}
extension LumaLevelsPixelModel {
public func isEqual(to nodeModel: NodeModel) -> Bool {
guard let pixelModel = nodeModel as? Self else { return false }
guard isPixelMergerEffectEqual(to: pixelModel) else { return false }
guard brightness == pixelModel.brightness else { return false }
guard darkness == pixelModel.darkness else { return false }
guard contrast == pixelModel.contrast else { return false }
guard gamma == pixelModel.gamma else { return false }
guard inverted == pixelModel.inverted else { return false }
guard smooth == pixelModel.smooth else { return false }
guard opacity == pixelModel.opacity else { return false }
guard offset == pixelModel.offset else { return false }
guard lumaGamma == pixelModel.lumaGamma else { return false }
return true
}
}
| 39.379845 | 125 | 0.609055 |
2f9337038dde91a455a12d536c794207b5c839d6 | 137 | import XCTest
import SwiftGraphQLServerTests
var tests = [XCTestCaseEntry]()
tests += SwiftGraphQLServerTests.allTests()
XCTMain(tests) | 19.571429 | 43 | 0.817518 |
f84cf311bacfa86bbe9f796af2c94eb5399861d9 | 4,416 | // The MIT License (MIT)
//
// Copyright (c) 2015-2019 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
class ImageDecoderTests: XCTestCase {
func testDecodingProgressiveJPEG() {
let data = Test.data(name: "progressive", extension: "jpeg")
let decoder = ImageDecoder()
// Just before the Start Of Frame
XCTAssertNil(decoder.decode(data: data[0...358], isFinal: false))
XCTAssertNil(decoder.isProgressive)
XCTAssertEqual(decoder.numberOfScans, 0)
// Right after the Start Of Frame
XCTAssertNil(decoder.decode(data: data[0...359], isFinal: false))
XCTAssertTrue(decoder.isProgressive!)
XCTAssertEqual(decoder.numberOfScans, 0) // still haven't finished the first scan
// Just before the first Start Of Scan
XCTAssertNil(decoder.decode(data: data[0...438], isFinal: false))
XCTAssertEqual(decoder.numberOfScans, 0) // still haven't finished the first scan
// Found the first Start Of Scan
XCTAssertNil(decoder.decode(data: data[0...439], isFinal: false))
XCTAssertEqual(decoder.numberOfScans, 1)
// Found the second Start of Scan
let scan1 = decoder.decode(data: data[0...2952], isFinal: false)
XCTAssertNotNil(scan1)
if let scan1 = scan1 {
#if os(macOS)
XCTAssertEqual(scan1.size.width, 450)
XCTAssertEqual(scan1.size.height, 300)
#else
XCTAssertEqual(scan1.size.width * scan1.scale, 450)
XCTAssertEqual(scan1.size.height * scan1.scale, 300)
#endif
}
XCTAssertEqual(decoder.numberOfScans, 2)
// Feed all data and see how many scans are there
// In practice the moment we finish receiving data we call
// `decode(data: data, isFinal: true)` so we might not scan all the
// of the bytes and encounter all of the scans (e.g. the final chunk
// of data that we receive contains multiple scans).
XCTAssertNotNil(decoder.decode(data: data, isFinal: false))
XCTAssertEqual(decoder.numberOfScans, 10)
}
func testDecodingGIFs() {
XCTAssertFalse(ImagePipeline.Configuration.isAnimatedImageDataEnabled)
let data = Test.data(name: "cat", extension: "gif")
XCTAssertNil(ImageDecoder().decode(data: data)?.animatedImageData)
ImagePipeline.Configuration.isAnimatedImageDataEnabled = true
XCTAssertNotNil(ImageDecoder().decode(data: data)?.animatedImageData)
ImagePipeline.Configuration.isAnimatedImageDataEnabled = false
}
}
class ImageFormatTests: XCTestCase {
// MARK: PNG
func testDetectPNG() {
let data = Test.data(name: "fixture", extension: "png")
XCTAssertNil(ImageFormat.format(for: data[0..<1]))
XCTAssertNil(ImageFormat.format(for: data[0..<7]))
XCTAssertEqual(ImageFormat.format(for: data[0..<8]), .png)
XCTAssertEqual(ImageFormat.format(for: data), .png)
}
// MARK: GIF
func testDetectGIF() {
let data = Test.data(name: "cat", extension: "gif")
XCTAssertEqual(ImageFormat.format(for: data), .gif)
}
// MARK: JPEG
func testDetectBaselineJPEG() {
let data = Test.data(name: "baseline", extension: "jpeg")
XCTAssertNil(ImageFormat.format(for: data[0..<1]))
XCTAssertNil(ImageFormat.format(for: data[0..<2]))
XCTAssertEqual(ImageFormat.format(for: data[0..<3]), .jpeg(isProgressive: nil))
XCTAssertEqual(ImageFormat.format(for: data), .jpeg(isProgressive: false))
}
func testDetectProgressiveJPEG() {
let data = Test.data(name: "progressive", extension: "jpeg")
// Not enough data
XCTAssertNil(ImageFormat.format(for: Data()))
XCTAssertNil(ImageFormat.format(for: data[0..<2]))
// Enough to determine image format
XCTAssertEqual(ImageFormat.format(for: data[0..<3]), .jpeg(isProgressive: nil))
XCTAssertEqual(ImageFormat.format(for: data[0...30]), .jpeg(isProgressive: nil))
// Just before the first scan
XCTAssertEqual(ImageFormat.format(for: data[0...358]), .jpeg(isProgressive: nil))
XCTAssertEqual(ImageFormat.format(for: data[0...359]), .jpeg(isProgressive: true))
// Full image
XCTAssertEqual(ImageFormat.format(for: data), .jpeg(isProgressive: true))
}
}
| 39.428571 | 90 | 0.654212 |
bb482e159e2a5bb1caa16c5c19cb5f7d02d7e6fe | 9,605 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 871. Minimum Number of Refueling Stops
// A car travels from a starting position to a destination which is target miles east of the starting position.
// There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.
// The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
// Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.
// Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
// Example 1:
// Input: target = 1, startFuel = 1, stations = []
// Output: 0
// Explanation: We can reach the target without refueling.
// Example 2:
// Input: target = 100, startFuel = 1, stations = [[10,100]]
// Output: -1
// Explanation: We can not reach the target (or even the first gas station).
// Example 3:
// Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
// Output: 2
// Explanation: We start with 10 liters of fuel.
// We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
// Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
// and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
// We made 2 refueling stops along the way, so we return 2.
// Constraints:
// 1 <= target, startFuel <= 10^9
// 0 <= stations.length <= 500
// 0 <= positioni <= positioni + 1 < target
// 1 <= fueli < 10^9
func minRefuelStops(_ target: Int, _ startFuel: Int, _ stations: [[Int]]) -> Int {
var pq = Heap<Int>(sort: >)
var maxDistance = startFuel
var stops = 0
var i = 0
while maxDistance < target {
// We maintain a max heap of the station that has the most gas, and is still
// reachable with what we have in our startFuel
while i < stations.count && stations[i][0] <= maxDistance {
pq.insert(stations[i][1])
i += 1
}
if pq.isEmpty { return -1 }
maxDistance += pq.remove()!
stops += 1
}
return stops
}
}
public struct Heap<T> {
/** The array that stores the heap's nodes. */
var nodes = [T]()
/**
* Determines how to compare two nodes in the heap.
* Use '>' for a max-heap or '<' for a min-heap,
* or provide a comparing method if the heap is made
* of custom elements, for example tuples.
*/
private var orderCriteria: (T, T) -> Bool
/**
* Creates an empty heap.
* The sort function determines whether this is a min-heap or max-heap.
* For comparable data types, > makes a max-heap, < makes a min-heap.
*/
public init(sort: @escaping (T, T) -> Bool) { self.orderCriteria = sort }
/**
* Creates a heap from an array. The order of the array does not matter;
* the elements are inserted into the heap in the order determined by the
* sort function. For comparable data types, '>' makes a max-heap,
* '<' makes a min-heap.
*/
public init(array: [T], sort: @escaping (T, T) -> Bool) {
self.orderCriteria = sort
configureHeap(from: array)
}
/**
* Configures the max-heap or min-heap from an array, in a bottom-up manner.
* Performance: This runs pretty much in O(n).
*/
private mutating func configureHeap(from array: [T]) {
nodes = array
for i in stride(from: (nodes.count/2-1), through: 0, by: -1) { shiftDown(i) }
}
public var isEmpty: Bool { nodes.isEmpty }
public var count: Int { nodes.count }
/**
* Returns the index of the parent of the element at index i.
* The element at index 0 is the root of the tree and has no parent.
*/
@inline(__always) internal func parentIndex(ofIndex i: Int) -> Int { (i - 1) / 2 }
/**
* Returns the index of the left child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no left child.
*/
@inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int { 2 * i + 1 }
/**
* Returns the index of the right child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no right child.
*/
@inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int { 2 * i + 2 }
/**
* Returns the maximum value in the heap (for a max-heap) or the minimum
* value (for a min-heap).
*/
public func peek() -> T? { nodes.first }
/**
* Adds a new value to the heap. This reorders the heap so that the max-heap
* or min-heap property still holds. Performance: O(log n).
*/
public mutating func insert(_ value: T) {
nodes.append(value)
shiftUp(nodes.count - 1)
}
/**
* Adds a sequence of values to the heap. This reorders the heap so that
* the max-heap or min-heap property still holds. Performance: O(log n).
*/
public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T {
for value in sequence { insert(value) }
}
/**
* Allows you to change an element. This reorders the heap so that
* the max-heap or min-heap property still holds.
*/
public mutating func replace(index i: Int, value: T) {
guard i < nodes.count else { return }
remove(at: i)
insert(value)
}
/**
* Removes the root node from the heap. For a max-heap, this is the maximum
* value; for a min-heap it is the minimum value. Performance: O(log n).
*/
@discardableResult public mutating func remove() -> T? {
guard !nodes.isEmpty else { return nil }
if nodes.count == 1 {
return nodes.removeLast()
} else {
// Use the last node to replace the first one, then fix the heap by
// shifting this new first node into its proper position.
let value = nodes[0]
nodes[0] = nodes.removeLast()
shiftDown(0)
return value
}
}
/**
* Removes an arbitrary node from the heap. Performance: O(log n).
* Note that you need to know the node's index.
*/
@discardableResult public mutating func remove(at index: Int) -> T? {
guard index < nodes.count else { return nil }
let size = nodes.count - 1
if index != size {
nodes.swapAt(index, size)
shiftDown(from: index, until: size)
shiftUp(index)
}
return nodes.removeLast()
}
/**
* Takes a child node and looks at its parents; if a parent is not larger
* (max-heap) or not smaller (min-heap) than the child, we exchange them.
*/
internal mutating func shiftUp(_ index: Int) {
var childIndex = index
let child = nodes[childIndex]
var parentIndex = self.parentIndex(ofIndex: childIndex)
while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {
nodes[childIndex] = nodes[parentIndex]
childIndex = parentIndex
parentIndex = self.parentIndex(ofIndex: childIndex)
}
nodes[childIndex] = child
}
/**
* Looks at a parent node and makes sure it is still larger (max-heap) or
* smaller (min-heap) than its childeren.
*/
internal mutating func shiftDown(from index: Int, until endIndex: Int) {
let leftChildIndex = self.leftChildIndex(ofIndex: index)
let rightChildIndex = leftChildIndex + 1
// Figure out which comes first if we order them by the sort function:
// the parent, the left child, or the right child. If the parent comes
// first, we're done. If not, that element is out-of-place and we make
// it "float down" the tree until the heap property is restored.
var first = index
if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) { first = leftChildIndex }
if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) { first = rightChildIndex }
if first == index { return }
nodes.swapAt(index, first)
shiftDown(from: first, until: endIndex)
}
internal mutating func shiftDown(_ index: Int) { shiftDown(from: index, until: nodes.count) }
}
// MARK: - Searching
extension Heap where T: Equatable {
/** Get the index of a node in the heap. Performance: O(n). */
public func index(of node: T) -> Int? { nodes.firstIndex(where: { $0 == node }) }
/** Removes the first occurrence of a node from the heap. Performance: O(n log n). */
@discardableResult public mutating func remove(node: T) -> T? {
if let index = index(of: node) { return remove(at: index) }
return nil
}
} | 33.820423 | 273 | 0.617595 |
56b3393638ed8b312ab5d9769b1cddde9edcab62 | 876 | import UIKit
public extension UIStoryboard {
/// Creates and returns a storyboard object for the specified storyboard resource file in the main bundle of the current application.
///
/// - Parameter name: The name of the storyboard resource file without the filename extension.
convenience init(name: String) {
self.init(name: name, bundle: nil)
}
/// Instantiate view controller using convention of storyboard identifier matching class name.
///
/// let storyboard = UIStoryboard("Main")
/// let controller: MyViewController = storyboard.instantiateViewController()
///
/// - Returns: Instantiated controller from storyboard, or nil if non existent.
func instantiateViewController<T: UIViewController>() -> T? {
instantiateViewController(withIdentifier: String(describing: T.self)) as? T
}
}
| 39.818182 | 137 | 0.700913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.