repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
haaakon/Indus-Valley
Indus ValleyTests/VolumeTests.swift
1
1140
// // Indus_ValleyTests.swift // Indus ValleyTests // // Created by Håkon Bogen on 19/04/15. // Copyright (c) 2015 haaakon. All rights reserved. // import UIKit import XCTest class VolumeTests: 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 testCreateVolume() { let singleLitre = Volume(quantity: 1, unit: .Litre) XCTAssert(singleLitre.quantity == 1, "one litre was not set with correct value") XCTAssert(singleLitre.unit == VolumeUnit.Litre, "one litre did not get correct unit") } func testCreateDesilitre() { let desilitre = Volume(quantity: 4, unit: .Desilitre) XCTAssert(desilitre.quantity == 4, "one desilitre was not set with correct value") XCTAssert(desilitre.unit == VolumeUnit.Desilitre, "one desilitre did not get correct unit") } }
mit
apple/swift-nio
Tests/NIOWebSocketTests/NIOWebSocketFrameAggregatorTests+XCTest.swift
1
2084
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // NIOWebSocketFrameAggregatorTests+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension NIOWebSocketFrameAggregatorTests { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (NIOWebSocketFrameAggregatorTests) -> () throws -> Void)] { return [ ("testEmptyButFinalFrameIsForwardedEvenIfMinNonFinalFragmentSizeIsGreaterThanZero", testEmptyButFinalFrameIsForwardedEvenIfMinNonFinalFragmentSizeIsGreaterThanZero), ("testTooSmallAndNonFinalFrameThrows", testTooSmallAndNonFinalFrameThrows), ("testTooBigFrameThrows", testTooBigFrameThrows), ("testTooBigAccumulatedFrameThrows", testTooBigAccumulatedFrameThrows), ("testTooManyFramesThrow", testTooManyFramesThrow), ("testAlmostTooManyFramesDoNotThrow", testAlmostTooManyFramesDoNotThrow), ("testTextFrameIsStillATextFrameAfterAggregation", testTextFrameIsStillATextFrameAfterAggregation), ("testPingFrameIsForwarded", testPingFrameIsForwarded), ("testPongFrameIsForwarded", testPongFrameIsForwarded), ("testCloseConnectionFrameIsForwarded", testCloseConnectionFrameIsForwarded), ("testFrameAggregationWithMask", testFrameAggregationWithMask), ] } }
apache-2.0
timd/ProiOSTableCollectionViews
Ch09/InCellCV/InCellCV/AppDelegate.swift
1
2136
// // AppDelegate.swift // InCellCV // // Created by Tim on 07/11/15. // Copyright © 2015 Tim Duckett. 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:. } }
mit
anzfactory/QiitaCollection
QiitaCollection/AnonymousAccount.swift
1
8056
// // AnonymousAccount.swift // QiitaCollection // // Created by ANZ on 2015/03/23. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class AnonymousAccount: NSObject { let qiitaApiManager: QiitaApiManager = QiitaApiManager.sharedInstance let userDataManager: UserDataManager = UserDataManager.sharedInstance func signin(code: String, completion: (qiitaAccount: QiitaAccount?) -> Void) { self.qiitaApiManager.postAuthorize(ThirdParty.Qiita.ClientID.rawValue, clientSecret: ThirdParty.Qiita.ClientSecret.rawValue, code: code) { (token, isError) -> Void in if isError { completion(qiitaAccount:nil); return } // 保存 self.userDataManager.setQiitaAccessToken(token) self.qiitaApiManager.getAuthenticatedUser({ (item, isError) -> Void in if isError { completion(qiitaAccount:nil) return } self.userDataManager.qiitaAuthenticatedUserID = item!.id let account = QiitaAccount() completion(qiitaAccount:account) }) } } func signout(completion: (anonymous: AnonymousAccount?) -> Void) { completion(anonymous: self) } func newEntries(page:Int, completion: (total: Int, items:[EntryEntity]) -> Void) { self.qiitaApiManager.getEntriesNew(page, completion: { (total, items, isError) -> Void in if isError { completion(total: 0, items: [EntryEntity]()) return } completion(total: total, items: items) }) } func searchEntries(page: Int, query:String, completion: (total: Int, items:[EntryEntity]) -> Void) { self.qiitaApiManager.getEntriesSearch(query, page: page) { (total, items, isError) -> Void in if isError { completion(total:0, items:[EntryEntity]()) return } completion(total: total, items: items) } } func read(entryId: String, completion: (entry: EntryEntity?) -> Void) { self.qiitaApiManager.getEntry(entryId, completion: { (item, isError) -> Void in if isError { completion(entry: nil) return } completion(entry: item!) }) } func hasDownloadFiles() -> Bool { return UserDataManager.sharedInstance.entryFiles.count > 0 } func downloadEntryTitles() -> [String] { return [String].convert(self.userDataManager.entryFiles, key: "title") } func downloadEntryId(atIndex: Int) -> String { let item: [String: String] = self.userDataManager.entryFiles[atIndex] if let id = item["id"] { return id } else { return "" } } func download(entry: EntryEntity, completion: (isError: Bool) -> Void) { let manager: FileManager = FileManager() manager.save(entry.id, dataString: entry.htmlBody, completion: { (isError) -> Void in if isError { completion(isError: true) return } self.userDataManager.appendSavedEntry(entry.id, title: entry.title) completion(isError: false) return }) } func loadLocalEntry(entryId: String, completion: (isError: Bool, title: String, body: String) -> Void) { // ローカルファイルから読み出す FileManager().read(entryId, completion: { (text) -> Void in if text.isEmpty { completion(isError:true, title: "", body: "") return } let title = UserDataManager.sharedInstance.titleSavedEntry(entryId) completion(isError: false, title: title, body: text) }) } func removeLocalEntry(atIndex: Int, completion: (isError: Bool, titles:[String]) -> Void) { let entryId: String = self.userDataManager.entryFiles[atIndex]["id"]! FileManager().remove(entryId, completion: { (isError) -> Void in if isError { completion(isError: true, titles:self.downloadEntryTitles()) return } self.userDataManager.removeEntry(entryId) completion(isError: false, titles:self.downloadEntryTitles()) }) } func pinEntryTitles() -> [String] { return [String].convert(self.userDataManager.pins, key: "title") } func pinEntryId(atIndex: Int) -> String { if let id = self.userDataManager.pins[atIndex]["id"] { return id } else { return "" } } func pin(entry: EntryEntity) { self.userDataManager.appendPinEntry(entry.id, entryTitle: entry.title) } func removePin(atIndex: Int) { self.userDataManager.clearPinEntry(atIndex) } func saveQueries() -> [[String: String]] { return self.userDataManager.queries } func saveQueryTitles() -> [String] { return [String].convert(self.userDataManager.queries, key: "title") } func saveQuery(query: String, title: String) { self.userDataManager.appendQuery(query, label: title) } func removeQuery(atIndex: Int) { self.userDataManager.clearQuery(atIndex) } func existsMuteUser(userId: String) -> Bool { return contains(self.userDataManager.muteUsers, userId) } func muteUserNames() -> [String] { return self.userDataManager.muteUsers } func muteUserId(atIndex: Int) -> String { return self.userDataManager.muteUsers[atIndex] } func cancelMute(atIndex: Int) { self.userDataManager.clearMutedUser(self.muteUserNames()[atIndex]) } func cancelMuteUser(userId: String) { self.userDataManager.clearMutedUser(userId) } func mute(userId: String) { self.userDataManager.appendMuteUserId(userId) } func comments(page: Int, entryId: String, completion: (total: Int, items:[CommentEntity]) -> Void) { self.qiitaApiManager.getEntriesComments(entryId, page: page) { (total, items, isError) -> Void in if isError { completion(total: 0, items: [CommentEntity]()) return } completion(total: total, items: items) } } func other(userId: String, completion: (user: OtherAccount?) -> Void) { self.qiitaApiManager.getUser(userId, completion: { (item, isError) -> Void in if item == nil { completion(user: nil) } else { completion(user: OtherAccount(qiitaId: item!.id)) } }) } func saveHistory(entry: EntryEntity) { ParseManager.sharedInstance.putHistory(entry) } func histories(page:Int, completion:(items: [HistoryEntity]) -> Void) { ParseManager.sharedInstance.getHistory(page, completion: { (items) -> Void in completion(items: items) }) } func weekRanking(completion: (items: [RankEntity]) -> Void) { ParseManager.sharedInstance.getWeekRanking(0, completion: { (items) -> Void in completion(items: items) }) } func adventList(year: Int, page: Int, completion: (items: [KimonoEntity]) -> Void) { ParseManager.sharedInstance.getAdventList(year, page: page) { (items) -> Void in completion(items: items) } } func adventEntires(objectId: String, completion: (items: [AdventEntity]) -> Void) { ParseManager.sharedInstance.getAdventEntries(objectId, completion: { (items) -> Void in completion(items:items) }) } }
mit
TCA-Team/iOS
TUM Campus App/CardCells/MVGStationCollectionViewCell.swift
1
956
// // MVGStationCollectionViewCell.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // 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. // // 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 UIKit class MVGStationCollectionViewCell: UICollectionViewCell { @IBOutlet weak var stationNameLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! }
gpl-3.0
ainame/Swift-WebP
Sources/WebP/WebPEncoderConfig.swift
1
8526
import Foundation import CWebP extension CWebP.WebPImageHint: ExpressibleByIntegerLiteral { /// Create an instance initialized to `value`. public init(integerLiteral value: Int) { switch UInt32(value) { case CWebP.WEBP_HINT_DEFAULT.rawValue: self = CWebP.WEBP_HINT_DEFAULT case CWebP.WEBP_HINT_PICTURE.rawValue: self = CWebP.WEBP_HINT_PICTURE case CWebP.WEBP_HINT_PHOTO.rawValue: self = CWebP.WEBP_HINT_PHOTO case CWebP.WEBP_HINT_GRAPH.rawValue: self = CWebP.WEBP_HINT_GRAPH default: fatalError() } } } // mapping from CWebP.WebPConfig public struct WebPEncoderConfig: InternalRawRepresentable { public enum WebPImageHint: CWebP.WebPImageHint { case `default` = 0 case picture = 1 case photo = 2 case graph = 3 } // Lossless encoding (0=lossy(default), 1=lossless). public var lossless: Int = 0 // between 0 (smallest file) and 100 (biggest) public var quality: Float // quality/speed trade-off (0=fast, 6=slower-better) public var method: Int // Hint for image type (lossless only for now). public var imageHint: WebPImageHint = .default // Parameters related to lossy compression only: // if non-zero, set the desired target size in bytes. // Takes precedence over the 'compression' parameter. public var targetSize: Int = 0 // if non-zero, specifies the minimal distortion to // try to achieve. Takes precedence over target_size. public var targetPSNR: Float = 0 // maximum number of segments to use, in [1..4] public var segments: Int // Spatial Noise Shaping. 0=off, 100=maximum. public var snsStrength: Int // range: [0 = off .. 100 = strongest] public var filterStrength: Int // range: [0 = off .. 7 = least sharp] public var filterSharpness: Int // filtering type: 0 = simple, 1 = strong (only used // if filter_strength > 0 or autofilter > 0) public var filterType: Int // Auto adjust filter's strength [0 = off, 1 = on] public var autofilter: Int // Algorithm for encoding the alpha plane (0 = none, // 1 = compressed with WebP lossless). Default is 1. public var alphaCompression: Int = 1 // Predictive filtering method for alpha plane. // 0: none, 1: fast, 2: best. Default if 1. public var alphaFiltering: Int // Between 0 (smallest size) and 100 (lossless). // Default is 100. public var alphaQuality: Int = 100 // number of entropy-analysis passes (in [1..10]). public var pass: Int // if true, export the compressed picture back. // In-loop filtering is not applied. public var showCompressed: Bool // preprocessing filter: // 0=none, 1=segment-smooth, 2=pseudo-random dithering public var preprocessing: Int // log2(number of token partitions) in [0..3]. Default // is set to 0 for easier progressive decoding. public var partitions: Int = 0 // quality degradation allowed to fit the 512k limit // on prediction modes coding (0: no degradation, // 100: maximum possible degradation). public var partitionLimit: Int // If true, compression parameters will be remapped // to better match the expected output size from // JPEG compression. Generally, the output size will // be similar but the degradation will be lower. public var emulateJpegSize: Bool // If non-zero, try and use multi-threaded encoding. public var threadLevel: Int // If set, reduce memory usage (but increase CPU use). public var lowMemory: Bool // Near lossless encoding [0 = max loss .. 100 = off // Int(default)]. public var nearLossless: Int = 100 // if non-zero, preserve the exact RGB values under // transparent area. Otherwise, discard this invisible // RGB information for better compression. The default // value is 0. public var exact: Int public var qmin: Int = 0 public var qmax: Int = 100 // reserved for future lossless feature var useDeltaPalette: Bool // if needed, use sharp (and slow) RGB->YUV conversion var useSharpYUV: Bool static public func preset(_ preset: Preset, quality: Float) -> WebPEncoderConfig { let webPConfig = preset.webPConfig(quality: quality) return WebPEncoderConfig(rawValue: webPConfig)! } internal init?(rawValue: CWebP.WebPConfig) { lossless = Int(rawValue.lossless) quality = rawValue.quality method = Int(rawValue.method) imageHint = WebPImageHint(rawValue: rawValue.image_hint)! targetSize = Int(rawValue.target_size) targetPSNR = Float(rawValue.target_PSNR) segments = Int(rawValue.segments) snsStrength = Int(rawValue.sns_strength) filterStrength = Int(rawValue.filter_strength) filterSharpness = Int(rawValue.filter_sharpness) filterType = Int(rawValue.filter_type) autofilter = Int(rawValue.autofilter) alphaCompression = Int(rawValue.alpha_compression) alphaFiltering = Int(rawValue.alpha_filtering) alphaQuality = Int(rawValue.alpha_quality) pass = Int(rawValue.pass) showCompressed = rawValue.show_compressed != 0 ? true : false preprocessing = Int(rawValue.preprocessing) partitions = Int(rawValue.partitions) partitionLimit = Int(rawValue.partition_limit) emulateJpegSize = rawValue.emulate_jpeg_size != 0 ? true : false threadLevel = Int(rawValue.thread_level) lowMemory = rawValue.low_memory != 0 ? true : false nearLossless = Int(rawValue.near_lossless) exact = Int(rawValue.exact) useDeltaPalette = rawValue.use_delta_palette != 0 ? true : false useSharpYUV = rawValue.use_sharp_yuv != 0 ? true : false qmin = Int(rawValue.qmin) qmax = Int(rawValue.qmax) } internal var rawValue: CWebP.WebPConfig { let show_compressed = showCompressed ? Int32(1) : Int32(0) let emulate_jpeg_size = emulateJpegSize ? Int32(1) : Int32(0) let low_memory = lowMemory ? Int32(1) : Int32(0) let use_delta_palette = useDeltaPalette ? Int32(1) : Int32(0) let use_sharp_yuv = useSharpYUV ? Int32(1) : Int32(0) return CWebP.WebPConfig( lossless: Int32(lossless), quality: Float(quality), method: Int32(method), image_hint: imageHint.rawValue, target_size: Int32(targetSize), target_PSNR: Float(targetPSNR), segments: Int32(segments), sns_strength: Int32(snsStrength), filter_strength: Int32(filterStrength), filter_sharpness: Int32(filterSharpness), filter_type: Int32(filterType), autofilter: Int32(autofilter), alpha_compression: Int32(alphaCompression), alpha_filtering: Int32(alphaFiltering), alpha_quality: Int32(alphaQuality), pass: Int32(pass), show_compressed: show_compressed, preprocessing: Int32(preprocessing), partitions: Int32(partitions), partition_limit: Int32(partitionLimit), emulate_jpeg_size: emulate_jpeg_size, thread_level: Int32(threadLevel), low_memory: low_memory, near_lossless: Int32(nearLossless), exact: Int32(exact), use_delta_palette: Int32(use_delta_palette), use_sharp_yuv: Int32(use_sharp_yuv), qmin: Int32(qmin), qmax: Int32(qmax) ) } public enum Preset { case `default`, picture, photo, drawing, icon, text func webPConfig(quality: Float) -> CWebP.WebPConfig { var config = CWebP.WebPConfig() switch self { case .default: WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, quality) case .picture: WebPConfigPreset(&config, WEBP_PRESET_PICTURE, quality) case .photo: WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality) case .drawing: WebPConfigPreset(&config, WEBP_PRESET_DRAWING, quality) case .icon: WebPConfigPreset(&config, WEBP_PRESET_ICON, quality) case .text: WebPConfigPreset(&config, WEBP_PRESET_TEXT, quality) } return config } } }
mit
SteveRohrlack/CitySimCore
src/Model/City/Budget.swift
1
372
// // Budget.swift // CitySimCore // // Created by Steve Rohrlack on 25.05.16. // Copyright © 2016 Steve Rohrlack. All rights reserved. // import Foundation /// the City Budget encapsulates all Budget related values public struct Budget { /// current budget public var amount: Int /// current total of running cost public var runningCost: Int }
mit
mindbody/Conduit
Tests/ConduitTests/Auth/OAuth2ExtensionTokenGrantTests.swift
1
2674
// // OAuth2ExtensionTokenGrantTests.swift // Conduit // // Created by John Hammerlund on 7/6/17. // Copyright © 2017 MINDBODY. All rights reserved. // import XCTest @testable import Conduit class OAuth2ExtensionTokenGrantTests: XCTestCase { let saml12GrantType = "urn:ietf:params:oauth:grant-type:sam12-bearer" let customParameters: [String: String] = ["assertion": "123abc"] private func makeStrategy() throws -> OAuth2ExtensionTokenGrantStrategy { let mockServerEnvironment = OAuth2ServerEnvironment(tokenGrantURL: try URL(absoluteString: "https://httpbin.org/get")) let mockClientConfiguration = OAuth2ClientConfiguration(clientIdentifier: "herp", clientSecret: "derp", environment: mockServerEnvironment, guestUsername: "clientuser", guestPassword: "abc123") let grantType = saml12GrantType var strategy = OAuth2ExtensionTokenGrantStrategy(grantType: grantType, clientConfiguration: mockClientConfiguration) strategy.tokenGrantRequestAdditionalBodyParameters = customParameters return strategy } func testAttemptsToIssueTokenViaExtensionGrant() throws { let sut = try makeStrategy() let request = try sut.buildTokenGrantRequest() guard let body = request.httpBody, let bodyParameters = AuthTestUtilities.deserialize(urlEncodedParameterData: body), let headers = request.allHTTPHeaderFields else { XCTFail("Expected header and body") return } XCTAssert(bodyParameters["grant_type"] == saml12GrantType) for parameter in customParameters { XCTAssert(bodyParameters[parameter.key] == parameter.value) } XCTAssert(request.httpMethod == "POST") XCTAssert(headers["Authorization"]?.contains("Basic") == true) } func testIssuesTokenWithCorrectSessionClient() throws { let operationQueue = OperationQueue() let sut = try makeStrategy() let completionExpectation = expectation(description: "completion handler executed") Auth.sessionClient = URLSessionClient(delegateQueue: operationQueue) sut.issueToken { result in XCTAssertNotNil(result.error) XCTAssert(OperationQueue.current == operationQueue) completionExpectation.fulfill() } waitForExpectations(timeout: 5) } func testIssuesTokenSync() throws { let sut = try makeStrategy() Auth.sessionClient = URLSessionClient(delegateQueue: OperationQueue()) XCTAssertThrowsError(try sut.issueToken()) } }
apache-2.0
Brsoyan/HBPhoneNumberFormatter
HBPhoneNumberFormatter-Swift/HBPhoneNumberFormatter.swift
1
8818
// // HBPhoneNumberFormatter.swift // HBPhoneNumberFormatter // // Created by Hovhannes Stepanyan on 6/11/18. // import UIKit class HBPhoneNumberFormatter: NSObject { var isShake: Bool = true var shakeSize: CGFloat = 5.0 var shakeDuration: CGFloat = 0.1 var shakeRepeatCount: CGFloat = 2.0 /// Create formatter and setup your custom formatting, like this @"(111) 1233-222" init(formatting: String) { super.init() let count = formatting.count var buffer = [unichar]() let _formatting = NSString(string: formatting) _formatting.getCharacters(&buffer, range: NSMakeRange(0, count)) for char in buffer { let character = String(char) if !self.isNumber(character) { symbols[String(buffer.index(of: char)!)] = character } } self.numberCount = formatting.count - symbols.count } /// Call this method from your uiviewcontroller <UITextFieldDelegate> similar method. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if !self.isNumber(string) { self.shake(textField: textField) return false } if range.length > 0 && self.prefix == textField.text { self.shake(textField: textField) return false } if range.length > 0 { self.isDelete = true } else { self.isDelete = false } let number = self.getNumber(textField.text) let numberCount = number.count if numberCount == self.numberCount { if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format: "%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if range.location == self.numberCount + self.symbols.count + self.prefix.count { self.shake(textField:textField) } if range.length == 0 { return false } } // TextField is Empty if textField.text?.count == self.prefix.count { if self.numberCount + self.symbols.count > (textField.text?.count ?? 0) { if var symbol = self.symbolFor(self.prefix.count) { if textField.text?.count != 0 { textField.text = String(format:"%@%@", textField.text! ,symbol) } else { textField.text = String(format:"%@" , symbol) } symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) textField.text = String(format:"%@%@", textField.text!, string) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } else { textField.text = String(format:"%@", string) let symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } } return false } // When added symbol in textField if textField.text?.count == range.location { if self.numberCount + self.symbols.count + self.prefix.count > (textField.text?.count ?? 0) { if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format:"%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if !self.isDelete && (textField.text?.count ?? 0) > 0 { textField.text = String(format:"%@%@", textField.text!, string) } if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format:"%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if self.isDelete { textField.text = String(format:"%@%@", textField.text!, string) } return false } return false } // Delete text from textField if range.length > 0 { if range.location >= self.prefix.count { if textField.text?.count == range.location { textField.text = textField.text?.substring(to: (textField.text?.endIndex)!) } else { textField.text = textField.text?.substring(to: String.Index.init(encodedOffset: range.location)) } if var symbol = self.symbolFor((textField.text?.count)! - 1) { while(true) { textField.text = textField.text!.substring(to: (textField.text?.endIndex)!) if let _symbol = self.symbolFor((textField.text?.count)! - 1) { symbol = _symbol break } } } } else { textField.text = textField.text!.substring(to: String.Index.init(encodedOffset: self.prefix.count)) } return false } return true } /// Set Contry code Prefix func setCountryName(_ name: String, textField: UITextField) { guard let code = CountryCode.countryCodeWith(name: name) else { print("We dosn't finde %@ .HB Default prefix is United States", name) self.prefix = CountryCode.countryCodeWith(name: "United States")! textField.text = String(format: "%@", self.prefix) return } self.prefix = code textField.text = String(format: "%@", code) } /// You can check your formatting is valid or not. func numberIsValidPhoneText(_ phoneText: String) -> Bool { let text = self.getNumber(phoneText) let length = text.count ?? 0 if length == self.numberCount && self.isNumber(text) { return true } else { return false } } // MARK: Private API private var symbols: Dictionary<String, Any> = [String: Any]() private var numberCount: Int = 0 private var isDelete: Bool = false private var prefix: String = "" private func isNumber(_ number: String) -> Bool { let digits = CharacterSet(charactersIn: "0123456789").inverted return NSString(string: number).rangeOfCharacter(from: digits).location == NSNotFound } private func shake(textField: UITextField) { if self.isShake { let shake = CABasicAnimation(keyPath:"position") shake.duration = CFTimeInterval(self.shakeDuration) shake.repeatCount = Float(self.shakeRepeatCount) shake.autoreverses = true shake.fromValue = NSValue(cgPoint: CGPoint(x: textField.center.x - self.shakeSize, y: textField.center.y)) shake.toValue = NSValue(cgPoint: CGPoint(x: textField.center.x + self.shakeSize, y: textField.center.y)) textField.layer.add(shake, forKey:"position") } } private func getNumber(_ mobileNumber: String?) -> String { let len = mobileNumber?.count ?? 0 var buffer = [unichar]() NSString(string: mobileNumber!).getCharacters(&buffer, range:NSMakeRange(0, len)) var number = "" for i in self.prefix.count..<len { let character = String(format:"%C", buffer[i]) if self.isNumber(character) { if number.count != 0 { number = String(format:"%@%@", number, character) } else { number = String(format:"%@", character) } } } return number; } private func symbolFor(_ index: Int?) -> String? { let _index = (index ?? 0) - self.prefix.count for key in self.symbols.keys { if key == String(_index) { return self.symbols[key] as? String; } } return nil } private func add(_ symbol: String, in textField: UITextField) { var _symbol = symbol while _symbol.count > 0 { textField.text = String(format:"%@%@", textField.text!, symbol) _symbol = self.symbolFor(textField.text?.count)! } } }
mit
fluidsonic/JetPack
Xcode/Tests/Support.swift
1
4687
import JetPack import XCTest struct EmptyStruct {} final class EmptyEqualObject: CustomStringConvertible, Hashable { init() {} var description: String { return "EmptyEqualObject(\(pointer(of: self)))" } func hash(into hasher: inout Hasher) {} } final class EmptyNonEqualObject: CustomStringConvertible, Hashable { init() {} var description: String { return "EmptyNonEqualObject(\(pointer(of: self)))" } func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } } func == (a: EmptyEqualObject, b: EmptyEqualObject) -> Bool { return true } func == (a: EmptyNonEqualObject, b: EmptyNonEqualObject) -> Bool { return a === b } func XCTAssertEqual<X: Equatable, Y: Equatable> (_ expression1: (X, Y)?, _ expression2: (X, Y)?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertTrue(expression1.0 == expression2.0 && expression1.1 == expression2.1, file: file, line: line) return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<X: Equatable, Y: Equatable> (_ expression1: [(X, Y)]?, _ expression2: [(X, Y)]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<T: Equatable> (_ expression1: [T]?, _ expression2: [T]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1, expression2, file: file, line: line) return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<T: Equatable> (_ expression1: [T?], _ expression2: [T?], file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } } func XCTAssertEqual<T: Equatable> (_ expression1: [T?]?, _ expression2: [T?]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: T?, _ expression2: T?, file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(expression1 === expression2, "\(String(describing: expression1)) is not identical to \(String(describing: expression2))", file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: [T]?, _ expression2: [T]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertIdentical(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: Set<T>?, _ expression2: Set<T>?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for (element1, element2) in zip(expression1, expression2) { XCTAssertIdentical(element1, element2, file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual(_ expression1: CGRect, _ expression2: CGRect, accuracy: CGFloat, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1.origin.x, expression2.origin.x, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.origin.y, expression2.origin.y, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.width, expression2.width, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.height, expression2.height, accuracy: accuracy, file: file, line: line) }
mit
tunespeak/AlamoRecord
Example/Pods/NotificationBannerSwift/NotificationBanner/Classes/GrowingNotificationBanner.swift
1
8777
/* The MIT License (MIT) Copyright (c) 2017-2018 Dalton Hinterscher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import SnapKit public class GrowingNotificationBanner: BaseNotificationBanner { public enum IconPosition { case top case center } /// The height of the banner when it is presented override public var bannerHeight: CGFloat { get { if let customBannerHeight = customBannerHeight { return customBannerHeight } else { // Calculate the height based on contents of labels // Determine available width for displaying the label var boundingWidth = UIScreen.main.bounds.width - padding * 2 // Substract safeAreaInsets from width, if available // We have to use keyWindow to ask for safeAreaInsets as `self` only knows its' safeAreaInsets in layoutSubviews if #available(iOS 11.0, *), let keyWindow = UIApplication.shared.keyWindow { let safeAreaOffset = keyWindow.safeAreaInsets.left + keyWindow.safeAreaInsets.right boundingWidth -= safeAreaOffset } if leftView != nil { boundingWidth -= iconSize + padding } if rightView != nil { boundingWidth -= iconSize + padding } let titleHeight = ceil(titleLabel?.text?.height( forConstrainedWidth: boundingWidth, font: titleFont ) ?? 0.0) let subtitleHeight = ceil(subtitleLabel?.text?.height( forConstrainedWidth: boundingWidth, font: subtitleFont ) ?? 0.0) let topOffset: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 44.0 : verticalSpacing let minHeight: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 88.0 : 64.0 var actualBannerHeight = topOffset + titleHeight + subtitleHeight + verticalSpacing if !subtitleHeight.isZero && !titleHeight.isZero { actualBannerHeight += innerSpacing } return max(actualBannerHeight, minHeight) } } set { customBannerHeight = newValue } } /// Spacing between the last label and the bottom edge of the banner private let verticalSpacing: CGFloat = 14.0 /// Spacing between title and subtitle private let innerSpacing: CGFloat = 2.5 /// The bottom most label of the notification if a subtitle is provided public private(set) var subtitleLabel: UILabel? /// The view that is presented on the left side of the notification private var leftView: UIView? /// The view that is presented on the right side of the notification private var rightView: UIView? /// Square size for left/right view if set private let iconSize: CGFloat = 24.0 /// Font used for the title label internal var titleFont: UIFont = UIFont.systemFont(ofSize: 17.5, weight: UIFont.Weight.bold) /// Font used for the subtitle label internal var subtitleFont: UIFont = UIFont.systemFont(ofSize: 15.0) public init(title: String? = nil, subtitle: String? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil, iconPosition: IconPosition = .center) { self.leftView = leftView self.rightView = rightView super.init(style: style, colors: colors) let labelsView = UIStackView() labelsView.axis = .vertical labelsView.spacing = innerSpacing let outerStackView = UIStackView() outerStackView.spacing = padding switch iconPosition { case .top: outerStackView.alignment = .top case .center: outerStackView.alignment = .center } if let leftView = leftView { outerStackView.addArrangedSubview(leftView) leftView.snp.makeConstraints { $0.size.equalTo(iconSize) } } outerStackView.addArrangedSubview(labelsView) if let title = title { titleLabel = UILabel() titleLabel!.font = titleFont titleLabel!.numberOfLines = 0 titleLabel!.textColor = .white titleLabel!.text = title titleLabel!.setContentHuggingPriority(.required, for: .vertical) labelsView.addArrangedSubview(titleLabel!) } if let subtitle = subtitle { subtitleLabel = UILabel() subtitleLabel!.font = subtitleFont subtitleLabel!.numberOfLines = 0 subtitleLabel!.textColor = .white subtitleLabel!.text = subtitle if title == nil { subtitleLabel!.setContentHuggingPriority(.required, for: .vertical) } labelsView.addArrangedSubview(subtitleLabel!) } if let rightView = rightView { outerStackView.addArrangedSubview(rightView) rightView.snp.makeConstraints { $0.size.equalTo(iconSize) } } contentView.addSubview(outerStackView) outerStackView.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.left.equalTo(safeAreaLayoutGuide).offset(padding) make.right.equalTo(safeAreaLayoutGuide).offset(-padding) } else { make.left.equalToSuperview().offset(padding) make.right.equalToSuperview().offset(-padding) } make.centerY.equalToSuperview() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public extension GrowingNotificationBanner { func applyStyling(cornerRadius: CGFloat? = nil, titleFont: UIFont? = nil, titleColor: UIColor? = nil, titleTextAlign: NSTextAlignment? = nil, subtitleFont: UIFont? = nil, subtitleColor: UIColor? = nil, subtitleTextAlign: NSTextAlignment? = nil) { if let cornerRadius = cornerRadius { contentView.layer.cornerRadius = cornerRadius } if let titleFont = titleFont { self.titleFont = titleFont titleLabel!.font = titleFont } if let titleColor = titleColor { titleLabel!.textColor = titleColor } if let titleTextAlign = titleTextAlign { titleLabel!.textAlignment = titleTextAlign } if let subtitleFont = subtitleFont { self.subtitleFont = subtitleFont subtitleLabel!.font = subtitleFont } if let subtitleColor = subtitleColor { subtitleLabel!.textColor = subtitleColor } if let subtitleTextAlign = subtitleTextAlign { subtitleLabel!.textAlignment = subtitleTextAlign } if titleFont != nil || subtitleFont != nil { updateBannerHeight() } } }
mit
arvedviehweger/swift
test/Prototypes/UnicodeDecoders.swift
1
91611
//===--- UnicodeDecoders.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-build-swift %s -Xfrontend -disable-access-control -swift-version 4 -g -Onone -o %T/UnicodeDecoders // RUN: %target-run %T/UnicodeDecoders // REQUIRES: executable_test // Benchmarking: use the following script with your swift-4-enabbled swiftc. // The BASELINE timings come from the existing standard library Codecs /* for x in BASELINE FORWARD REVERSE SEQUENCE COLLECTION REVERSE_COLLECTION ; do echo $x swiftc -DBENCHMARK -D$x -O -swift-version 4 UnicodeDecoders.swift -o /tmp/u3-$x for i in {1..3}; do (time nice -19 /tmp/u3-$x) 2>&1 | grep user done done */ //===----------------------------------------------------------------------===// extension UnicodeScalar { // Hack providing an efficient API that is available to the standard library @_versioned @inline(__always) init(_unchecked x: UInt32) { self = unsafeBitCast(x, to: UnicodeScalar.self) } static var replacementCharacter: UnicodeScalar { return UnicodeScalar(_unchecked: 0xfffd) } } //===----------------------------------------------------------------------===// @_fixed_layout public struct _UIntBuffer< Storage: UnsignedInteger & FixedWidthInteger, Element: UnsignedInteger & FixedWidthInteger > { @_versioned var _storage: Storage @_versioned var _bitCount: UInt8 @inline(__always) @_versioned internal init(_storage: Storage, _bitCount: UInt8) { self._storage = _storage self._bitCount = _bitCount } @inline(__always) public init(containing e: Element) { _storage = Storage(extendingOrTruncating: e) _bitCount = UInt8(extendingOrTruncating: Element.bitWidth) } } extension _UIntBuffer : Sequence { @_fixed_layout public struct Iterator : IteratorProtocol, Sequence { @inline(__always) public init(_ x: _UIntBuffer) { _impl = x } @inline(__always) public mutating func next() -> Element? { if _impl._bitCount == 0 { return nil } defer { _impl._storage = _impl._storage &>> Element.bitWidth _impl._bitCount = _impl._bitCount &- _impl._elementWidth } return Element(extendingOrTruncating: _impl._storage) } @_versioned var _impl: _UIntBuffer } @inline(__always) public func makeIterator() -> Iterator { return Iterator(self) } } extension _UIntBuffer : Collection { public typealias _Element = Element public struct Index : Comparable { @_versioned var bitOffset: UInt8 @_versioned init(bitOffset: UInt8) { self.bitOffset = bitOffset } public static func == (lhs: Index, rhs: Index) -> Bool { return lhs.bitOffset == rhs.bitOffset } public static func < (lhs: Index, rhs: Index) -> Bool { return lhs.bitOffset < rhs.bitOffset } } public var startIndex : Index { @inline(__always) get { return Index(bitOffset: 0) } } public var endIndex : Index { @inline(__always) get { return Index(bitOffset: _bitCount) } } @inline(__always) public func index(after i: Index) -> Index { return Index(bitOffset: i.bitOffset &+ _elementWidth) } @_versioned internal var _elementWidth : UInt8 { return UInt8(extendingOrTruncating: Element.bitWidth) } public subscript(i: Index) -> Element { @inline(__always) get { return Element(extendingOrTruncating: _storage &>> i.bitOffset) } } } extension _UIntBuffer : BidirectionalCollection { @inline(__always) public func index(before i: Index) -> Index { return Index(bitOffset: i.bitOffset &- _elementWidth) } } extension _UIntBuffer : RandomAccessCollection { public typealias Indices = DefaultRandomAccessIndices<_UIntBuffer> public typealias IndexDistance = Int @inline(__always) public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { let x = IndexDistance(i.bitOffset) &+ n &* Element.bitWidth return Index(bitOffset: UInt8(extendingOrTruncating: x)) } @inline(__always) public func distance(from i: Index, to j: Index) -> IndexDistance { return (Int(j.bitOffset) &- Int(i.bitOffset)) / Element.bitWidth } } extension FixedWidthInteger { @inline(__always) @_versioned func _fullShiftLeft<N: FixedWidthInteger>(_ n: N) -> Self { return (self &<< ((n &+ 1) &>> 1)) &<< (n &>> 1) } @inline(__always) @_versioned func _fullShiftRight<N: FixedWidthInteger>(_ n: N) -> Self { return (self &>> ((n &+ 1) &>> 1)) &>> (n &>> 1) } @inline(__always) @_versioned static func _lowBits<N: FixedWidthInteger>(_ n: N) -> Self { return ~((~0 as Self)._fullShiftLeft(n)) } } extension Range { @inline(__always) @_versioned func _contains_(_ other: Range) -> Bool { return other.clamped(to: self) == other } } extension _UIntBuffer : RangeReplaceableCollection { @inline(__always) public init() { _storage = 0 _bitCount = 0 } public var capacity: Int { return Storage.bitWidth / Element.bitWidth } @inline(__always) public mutating func append(_ newElement: Element) { _debugPrecondition(count < capacity) _storage |= Storage(newElement) &<< _bitCount _bitCount = _bitCount &+ _elementWidth } @inline(__always) public mutating func replaceSubrange<C: Collection>( _ target: Range<Index>, with replacement: C ) where C._Element == Element { _debugPrecondition( (0..<_bitCount)._contains_( target.lowerBound.bitOffset..<target.upperBound.bitOffset)) let replacement1 = _UIntBuffer(replacement) let targetCount = distance( from: target.lowerBound, to: target.upperBound) let growth = replacement1.count &- targetCount _debugPrecondition(count + growth <= capacity) let headCount = distance(from: startIndex, to: target.lowerBound) let tailOffset = distance(from: startIndex, to: target.upperBound) let w = Element.bitWidth let headBits = _storage & ._lowBits(headCount &* w) let tailBits = _storage._fullShiftRight(tailOffset &* w) _storage = headBits _storage |= replacement1._storage &<< (headCount &* w) _storage |= tailBits &<< ((tailOffset &+ growth) &* w) _bitCount = UInt8( extendingOrTruncating: IndexDistance(_bitCount) &+ growth &* w) } } //===----------------------------------------------------------------------===// public enum Unicode { public typealias UTF8 = Swift.UTF8 public typealias UTF16 = Swift.UTF16 public typealias UTF32 = Swift.UTF32 } extension Unicode { public enum ParseResult<T> { case valid(T) case emptyInput case invalid(length: Int) var isEmpty : Bool { switch self { case .emptyInput: return true default: return false } } } } public protocol UnicodeDecoder { associatedtype CodeUnit : UnsignedInteger, FixedWidthInteger associatedtype Buffer : Collection where Buffer.Iterator.Element == CodeUnit associatedtype EncodedScalar : Collection where EncodedScalar.Iterator.Element == CodeUnit static var replacement: EncodedScalar { get } init() var buffer: Buffer { get } mutating func parseOne<I : IteratorProtocol>( _ input: inout I ) -> Unicode.ParseResult<EncodedScalar> where I.Element == CodeUnit static func decodeOne(_ content: EncodedScalar) -> UnicodeScalar } extension UnicodeDecoder { @inline(__always) @discardableResult public static func decode<I: IteratorProtocol>( _ input: inout I, repairingIllFormedSequences makeRepairs: Bool, into output: (UnicodeScalar)->Void ) -> Int where I.Element == CodeUnit { var errors = 0 var d = Self() while true { switch d.parseOne(&input) { case let .valid(scalarContent): output(decodeOne(scalarContent)) case .invalid: if !makeRepairs { return 1 } errors += 1 output(UnicodeScalar(_unchecked: 0xFFFD)) case .emptyInput: return errors } } } } extension Unicode { struct ParsingIterator< CodeUnits : IteratorProtocol, Decoder: UnicodeDecoder > where Decoder.CodeUnit == CodeUnits.Element { var codeUnits: CodeUnits var decoder: Decoder } } extension Unicode.ParsingIterator : IteratorProtocol, Sequence { mutating func next() -> Decoder.EncodedScalar? { switch decoder.parseOne(&codeUnits) { case let .valid(scalarContent): return scalarContent case .invalid: return Decoder.replacement case .emptyInput: return nil } } } extension Unicode { struct DefaultScalarView< CodeUnits: BidirectionalCollection, Encoding: UnicodeEncoding > where CodeUnits.Iterator.Element == Encoding.CodeUnit { var codeUnits: CodeUnits init( _ codeUnits: CodeUnits, fromEncoding _: Encoding.Type = Encoding.self) { self.codeUnits = codeUnits } } } extension Unicode.DefaultScalarView : Sequence { struct Iterator { var parsing: Unicode.ParsingIterator< CodeUnits.Iterator, Encoding.ForwardDecoder > } func makeIterator() -> Iterator { return Iterator( parsing: Unicode.ParsingIterator( codeUnits: codeUnits.makeIterator(), decoder: Encoding.ForwardDecoder() )) } } extension Unicode.DefaultScalarView.Iterator : IteratorProtocol, Sequence { mutating func next() -> UnicodeScalar? { return parsing.next().map { Encoding.ForwardDecoder.decodeOne($0) } } } extension Unicode.DefaultScalarView { struct Index { var codeUnitIndex: CodeUnits.Index var scalar: UnicodeScalar var stride: UInt8 } } extension Unicode.DefaultScalarView.Index : Comparable { @inline(__always) public static func < ( lhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index, rhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index ) -> Bool { return lhs.codeUnitIndex < rhs.codeUnitIndex } @inline(__always) public static func == ( lhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index, rhs: Unicode.DefaultScalarView<CodeUnits,Encoding>.Index ) -> Bool { return lhs.codeUnitIndex == rhs.codeUnitIndex } } extension Unicode.DefaultScalarView : Collection { public var startIndex: Index { @inline(__always) get { return index( after: Index( codeUnitIndex: codeUnits.startIndex, scalar: UnicodeScalar(_unchecked: 0), stride: 0) ) } } public var endIndex: Index { @inline(__always) get { return Index( codeUnitIndex: codeUnits.endIndex, scalar: UnicodeScalar(_unchecked: 0), stride: 0) } } public subscript(i: Index) -> UnicodeScalar { @inline(__always) get { return i.scalar } } @inline(__always) public func index(after i: Index) -> Index { let nextPosition = codeUnits.index( i.codeUnitIndex, offsetBy: numericCast(i.stride)) var i = IndexingIterator( _elements: codeUnits, _position: nextPosition ) var d = Encoding.ForwardDecoder() switch d.parseOne(&i) { case .valid(let scalarContent): return Index( codeUnitIndex: nextPosition, scalar: Encoding.ForwardDecoder.decodeOne(scalarContent), stride: numericCast(scalarContent.count)) case .invalid(let stride): return Index( codeUnitIndex: nextPosition, scalar: UnicodeScalar(_unchecked: 0xfffd), stride: numericCast(stride)) case .emptyInput: return endIndex } } } // This should go in the standard library; see // https://github.com/apple/swift/pull/9074 and // https://bugs.swift.org/browse/SR-4721 @_fixed_layout public struct ReverseIndexingIterator< Elements : BidirectionalCollection > : IteratorProtocol, Sequence { @_inlineable @inline(__always) /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements, _position: Elements.Index) { self._elements = _elements self._position = _position } @_inlineable @inline(__always) public mutating func next() -> Elements._Element? { guard _fastPath(_position != _elements.startIndex) else { return nil } _position = _elements.index(before: _position) return _elements[_position] } @_versioned internal let _elements: Elements @_versioned internal var _position: Elements.Index } extension Unicode.DefaultScalarView : BidirectionalCollection { @inline(__always) public func index(before i: Index) -> Index { var d = Encoding.ReverseDecoder() var more = ReverseIndexingIterator( _elements: codeUnits, _position: i.codeUnitIndex) switch d.parseOne(&more) { case .valid(let scalarContent): let d: CodeUnits.IndexDistance = -numericCast(scalarContent.count) return Index( codeUnitIndex: codeUnits.index(i.codeUnitIndex, offsetBy: d), scalar: Encoding.ReverseDecoder.decodeOne(scalarContent), stride: numericCast(scalarContent.count)) case .invalid(let stride): let d: CodeUnits.IndexDistance = -numericCast(stride) return Index( codeUnitIndex: codeUnits.index(i.codeUnitIndex, offsetBy: d) , scalar: UnicodeScalar(_unchecked: 0xfffd), stride: numericCast(stride)) case .emptyInput: fatalError("index out of bounds.") } } } public protocol UnicodeEncoding { associatedtype CodeUnit associatedtype ForwardDecoder : UnicodeDecoder where ForwardDecoder.CodeUnit == CodeUnit associatedtype ReverseDecoder : UnicodeDecoder where ReverseDecoder.CodeUnit == CodeUnit } public protocol _UTFDecoderBase : UnicodeDecoder where Buffer == EncodedScalar { associatedtype BufferStorage = UInt32 } public protocol _UTFDecoder : _UTFDecoderBase where Buffer == _UIntBuffer<BufferStorage, CodeUnit>, BufferStorage == UInt32 { static func _isScalar(_: CodeUnit) -> Bool func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) var buffer: Buffer { get set } } extension _UTFDecoder { public mutating func parseOne<I : IteratorProtocol>( _ input: inout I ) -> Unicode.ParseResult<EncodedScalar> where I.Element == CodeUnit { // Bufferless single-scalar fastpath. if _fastPath(buffer.isEmpty) { guard let codeUnit = input.next() else { return .emptyInput } // ASCII, return immediately. if Self._isScalar(codeUnit) { return .valid(EncodedScalar(containing: codeUnit)) } // Non-ASCII, proceed to buffering mode. buffer.append(codeUnit) } else if Self._isScalar(CodeUnit(extendingOrTruncating: buffer._storage)) { // ASCII in buffer. We don't refill the buffer so we can return // to bufferless mode once we've exhausted it. let codeUnit = CodeUnit(extendingOrTruncating: buffer._storage) buffer.remove(at: buffer.startIndex) return .valid(EncodedScalar(containing: codeUnit)) } // Buffering mode. // Fill buffer back to 4 bytes (or as many as are left in the iterator). _sanityCheck(buffer._bitCount < 32) repeat { if let codeUnit = input.next() { buffer.append(codeUnit) } else { if buffer.isEmpty { return .emptyInput } break // We still have some bytes left in our buffer. } } while buffer._bitCount < 32 // Find one unicode scalar. let (isValid, scalarBitCount) = _parseMultipleCodeUnits() _sanityCheck(scalarBitCount % numericCast(CodeUnit.bitWidth) == 0) _sanityCheck(1...4 ~= scalarBitCount / 8) _sanityCheck(scalarBitCount <= buffer._bitCount) // Consume the decoded bytes (or maximal subpart of ill-formed sequence). var encodedScalar = buffer encodedScalar._bitCount = scalarBitCount buffer._storage = UInt32( // widen to 64 bits so that we can empty the buffer in the 4-byte case extendingOrTruncating: UInt64(buffer._storage) &>> scalarBitCount) buffer._bitCount = buffer._bitCount &- scalarBitCount if _fastPath(isValid) { return .valid(encodedScalar) } return .invalid( length: Int(scalarBitCount / numericCast(CodeUnit.bitWidth))) } } //===----------------------------------------------------------------------===// //===--- UTF8 Decoders ----------------------------------------------------===// //===----------------------------------------------------------------------===// public protocol _UTF8Decoder : _UTFDecoder { var buffer: Buffer { get set } } extension _UTF8Decoder { public static func _isScalar(_ x: CodeUnit) -> Bool { return x & 0x80 == 0 } } extension Unicode.UTF8 : UnicodeEncoding { public struct ForwardDecoder { public typealias Buffer = _UIntBuffer<UInt32, UInt8> public init() { buffer = Buffer() } public var buffer: Buffer } public struct ReverseDecoder { public typealias Buffer = _UIntBuffer<UInt32, UInt8> public init() { buffer = Buffer() } public var buffer: Buffer } } extension UTF8.ReverseDecoder : _UTF8Decoder { public typealias CodeUnit = UInt8 public typealias EncodedScalar = Buffer public static var replacement : EncodedScalar { return EncodedScalar(_storage: 0xefbfbd, _bitCount: 24) } public static func decodeOne(_ source: EncodedScalar) -> UnicodeScalar { let bits = source._storage switch source._bitCount { case 8: return UnicodeScalar(_unchecked: bits) case 16: var value = bits & 0b0______________________11_1111 value |= bits &>> 2 & 0b0______________0111__1100_0000 return UnicodeScalar(_unchecked: value) case 24: var value = bits & 0b0______________________11_1111 value |= bits &>> 2 & 0b0______________1111__1100_0000 value |= bits &>> 4 & 0b0_________1111_0000__0000_0000 return UnicodeScalar(_unchecked: value) default: _sanityCheck(source._bitCount == 32) var value = bits & 0b0______________________11_1111 value |= bits &>> 2 & 0b0______________1111__1100_0000 value |= bits &>> 4 & 0b0_____11__1111_0000__0000_0000 value |= bits &>> 6 & 0b0_1_1100__0000_0000__0000_0000 return UnicodeScalar(_unchecked: value) } } public // @testable func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _sanityCheck(buffer._storage & 0x80 != 0) // this case handled elsewhere if buffer._storage & 0b0__1110_0000__1100_0000 == 0b0__1100_0000__1000_0000 { // 2-byte sequence. Top 4 bits of decoded result must be nonzero let top4Bits = buffer._storage & 0b0__0001_1110__0000_0000 if _fastPath(top4Bits != 0) { return (true, 2*8) } } else if buffer._storage & 0b0__1111_0000__1100_0000__1100_0000 == 0b0__1110_0000__1000_0000__1000_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = buffer._storage & 0b0__1111__0010_0000__0000_0000 if _fastPath( top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) { return (true, 3*8) } } else if buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000__1000_0000 { // Make sure the top 5 bits of the decoded result would be in range let top5bits = buffer._storage & 0b0__0111__0011_0000__0000_0000__0000_0000 if _fastPath( top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that ends with the LSB of /// buffer. @inline(never) func _invalidLength() -> UInt8 { if buffer._storage & 0b0__1111_0000__1100_0000 == 0b0__1110_0000__1000_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = buffer._storage & 0b0__1111__0010_0000 if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 } } else if buffer._storage & 0b1111_1000__1100_0000 == 0b1111_0000__1000_0000 { // 2-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = buffer._storage & 0b0__0111__0011_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 } } else if buffer._storage & 0b0__1111_1000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000 { // 3-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = buffer._storage & 0b0__0111__0011_0000__0000_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 { return 3 } } return 1 } } extension Unicode.UTF8.ForwardDecoder : _UTF8Decoder { public typealias CodeUnit = UInt8 public typealias EncodedScalar = Buffer public static var replacement : EncodedScalar { return EncodedScalar(_storage: 0xbdbfef, _bitCount: 24) } public // @testable func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _sanityCheck(buffer._storage & 0x80 != 0) // this case handled elsewhere if buffer._storage & 0b0__1100_0000__1110_0000 == 0b0__1000_0000__1100_0000 { // 2-byte sequence. At least one of the top 4 bits of the decoded result // must be nonzero. if _fastPath(buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) } } else if buffer._storage & 0b0__1100_0000__1100_0000__1111_0000 == 0b0__1000_0000__1000_0000__1110_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = buffer._storage & 0b0___0010_0000__0000_1111 if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) { return (true, 3*8) } } else if buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000 == 0b0__1000_0000__1000_0000__1000_0000__1111_0000 { // 4-byte sequence. The top 5 bits of the decoded result must be nonzero // and no greater than 0b0__0100_0000 let top5bits = UInt16(buffer._storage & 0b0__0011_0000__0000_0111) if _fastPath( top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that starts with the LSB of /// buffer. @inline(never) func _invalidLength() -> UInt8 { if buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(buffer._storage & 0b0__0011_0000__0000_0111).byteSwapped if top5bits != 0 && top5bits <= 0b0__0000_0100__0000_0000 { return buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } public static func decodeOne(_ source: EncodedScalar) -> UnicodeScalar { let bits = source._storage switch source._bitCount { case 8: return UnicodeScalar(_unchecked: bits) case 16: var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8 value |= (bits & 0b0________________________________0001_1111) &<< 6 return UnicodeScalar(_unchecked: value) case 24: var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16 value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2 value |= (bits & 0b0________________________________0000_1111) &<< 12 return UnicodeScalar(_unchecked: value) default: _sanityCheck(source.count == 4) var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24 value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10 value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4 value |= (bits & 0b0________________________________0000_0111) &<< 18 return UnicodeScalar(_unchecked: value) } } } //===----------------------------------------------------------------------===// //===--- UTF-16 Decoders --------------------------------------------------===// //===----------------------------------------------------------------------===// public protocol _UTF16Decoder : _UTFDecoder where CodeUnit == UTF16.CodeUnit { var buffer: Buffer { get set } static var _surrogatePattern : UInt32 { get } } extension _UTF16Decoder { public static var replacement : EncodedScalar { return EncodedScalar(_storage: 0xFFFD, _bitCount: 16) } public static func _isScalar(_ x: CodeUnit) -> Bool { return x & 0xf800 != 0xd800 } public // @testable func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _sanityCheck( // this case handled elsewhere !Self._isScalar(UInt16(extendingOrTruncating: buffer._storage))) if _fastPath(buffer._storage & 0xFC00_FC00 == Self._surrogatePattern) { return (true, 2*16) } return (false, 1*16) } } extension Unicode.UTF16 : UnicodeEncoding { public struct ForwardDecoder { public typealias Buffer = _UIntBuffer<UInt32, UInt16> public init() { buffer = Buffer() } public var buffer: Buffer } public struct ReverseDecoder { public typealias Buffer = _UIntBuffer<UInt32, UInt16> public init() { buffer = Buffer() } public var buffer: Buffer } } extension UTF16.ReverseDecoder : _UTF16Decoder { public typealias CodeUnit = UInt16 public typealias EncodedScalar = Buffer public static var _surrogatePattern : UInt32 { return 0xD800_DC00 } public static func decodeOne(_ source: EncodedScalar) -> UnicodeScalar { let bits = source._storage if _fastPath(source._bitCount == 16) { return UnicodeScalar(_unchecked: bits & 0xffff) } _sanityCheck(source._bitCount == 32) let value = 0x10000 + ((bits & 0x03ff0000) &>> 6 | (bits & 0x03ff)) return UnicodeScalar(_unchecked: value) } } extension Unicode.UTF16.ForwardDecoder : _UTF16Decoder { public typealias CodeUnit = UInt16 public typealias EncodedScalar = Buffer public static var _surrogatePattern : UInt32 { return 0xDC00_D800 } public static func decodeOne(_ source: EncodedScalar) -> UnicodeScalar { let bits = source._storage if _fastPath(source._bitCount == 16) { return UnicodeScalar(_unchecked: bits & 0xffff) } _sanityCheck(source._bitCount == 32) let value = 0x10000 + (bits >> 16 & 0x03ff | (bits & 0x03ff) << 10) return UnicodeScalar(_unchecked: value) } } #if !BENCHMARK //===--- testing ----------------------------------------------------------===// import StdlibUnittest import SwiftPrivate func checkDecodeUTF<Codec : UnicodeCodec & UnicodeEncoding>( _ codec: Codec.Type, _ expectedHead: [UInt32], _ expectedRepairedTail: [UInt32], _ utfStr: [Codec.CodeUnit] ) -> AssertionResult { var decoded = [UInt32]() var expected = expectedHead func output(_ scalar: UInt32) { decoded.append(scalar) } func output1(_ scalar: UnicodeScalar) { decoded.append(scalar.value) } var result = assertionSuccess() func check<C: Collection>(_ expected: C, _ description: String) where C.Iterator.Element == UInt32 { if !expected.elementsEqual(decoded) { if result.description == "" { result = assertionFailure() } result = result.withDescription(" [\(description)]\n") .withDescription("expected: \(asHex(expectedHead))\n") .withDescription("actual: \(asHex(decoded))") } decoded.removeAll(keepingCapacity: true) } //===--- Tests without repairs ------------------------------------------===// do { let iterator = utfStr.makeIterator() _ = transcode( iterator, from: codec, to: UTF32.self, stoppingOnError: true, into: output) } check(expected, "legacy, repairing: false") do { var iterator = utfStr.makeIterator() let errorCount = Codec.ForwardDecoder.decode( &iterator, repairingIllFormedSequences: false, into: output1) expectEqual(expectedRepairedTail.isEmpty ? 0 : 1, errorCount) } check(expected, "forward, repairing: false") do { var iterator = utfStr.reversed().makeIterator() let errorCount = Codec.ReverseDecoder.decode( &iterator, repairingIllFormedSequences: false, into: output1) if expectedRepairedTail.isEmpty { expectEqual(0, errorCount) check(expected.reversed(), "reverse, repairing: false") } else { expectEqual(1, errorCount) let x = (expected + expectedRepairedTail).reversed() expectTrue( x.starts(with: decoded), "reverse, repairing: false\n\t\(Array(x)) does not start with \(decoded)") decoded.removeAll(keepingCapacity: true) } } //===--- Tests with repairs ------------------------------------------===// expected += expectedRepairedTail do { let iterator = utfStr.makeIterator() _ = transcode(iterator, from: codec, to: UTF32.self, stoppingOnError: false, into: output) } check(expected, "legacy, repairing: true") do { var iterator = utfStr.makeIterator() let errorCount = Codec.ForwardDecoder.decode( &iterator, repairingIllFormedSequences: true, into: output1) if expectedRepairedTail.isEmpty { expectEqual(0, errorCount) } else { expectNotEqual(0, errorCount) } } check(expected, "forward, repairing: true") do { var iterator = utfStr.reversed().makeIterator() let errorCount = Codec.ReverseDecoder.decode( &iterator, repairingIllFormedSequences: true, into: output1) if expectedRepairedTail.isEmpty { expectEqual(0, errorCount) } else { expectNotEqual(0, errorCount) } } check(expected.reversed(), "reverse, repairing: true") let scalars = Unicode.DefaultScalarView(utfStr, fromEncoding: Codec.self) expectEqualSequence(expected, scalars.map { $0.value }) expectEqualSequence( expected.reversed(), scalars.reversed().map { $0.value }) do { var x = scalars.makeIterator() var j = scalars.startIndex while (j != scalars.endIndex) { expectEqual(x.next()!, scalars[j]) j = scalars.index(after: j) } expectNil(x.next()) } return result } func checkDecodeUTF8( _ expectedHead: [UInt32], _ expectedRepairedTail: [UInt32], _ utf8Str: [UInt8] ) -> AssertionResult { return checkDecodeUTF(UTF8.self, expectedHead, expectedRepairedTail, utf8Str) } func checkDecodeUTF16( _ expectedHead: [UInt32], _ expectedRepairedTail: [UInt32], _ utf16Str: [UInt16] ) -> AssertionResult { return checkDecodeUTF(UTF16.self, expectedHead, expectedRepairedTail, utf16Str) } /* func checkDecodeUTF32( _ expectedHead: [UInt32], _ expectedRepairedTail: [UInt32], _ utf32Str: [UInt32] ) -> AssertionResult { return checkDecodeUTF(UTF32.self, expectedHead, expectedRepairedTail, utf32Str) } */ func checkEncodeUTF8(_ expected: [UInt8], _ scalars: [UInt32]) -> AssertionResult { var encoded = [UInt8]() let output: (UInt8) -> Void = { encoded.append($0) } let iterator = scalars.makeIterator() let hadError = transcode( iterator, from: UTF32.self, to: UTF8.self, stoppingOnError: true, into: output) expectFalse(hadError) if expected != encoded { return assertionFailure() .withDescription("\n") .withDescription("expected: \(asHex(expected))\n") .withDescription("actual: \(asHex(encoded))") } return assertionSuccess() } var UTF8Decoder = TestSuite("UTF8Decoder") //===----------------------------------------------------------------------===// public struct UTFTest { public struct Flags : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let utf8IsInvalid = Flags(rawValue: 1 << 0) public static let utf16IsInvalid = Flags(rawValue: 1 << 1) } public let string: String public let utf8: [UInt8] public let utf16: [UInt16] public let unicodeScalars: [UnicodeScalar] public let unicodeScalarsRepairedTail: [UnicodeScalar] public let flags: Flags public let loc: SourceLoc public var utf32: [UInt32] { return unicodeScalars.map(UInt32.init) } public var utf32RepairedTail: [UInt32] { return unicodeScalarsRepairedTail.map(UInt32.init) } public init( string: String, utf8: [UInt8], utf16: [UInt16], scalars: [UInt32], scalarsRepairedTail: [UInt32] = [], flags: Flags = [], file: String = #file, line: UInt = #line ) { self.string = string self.utf8 = utf8 self.utf16 = utf16 self.unicodeScalars = scalars.map { UnicodeScalar($0)! } self.unicodeScalarsRepairedTail = scalarsRepairedTail.map { UnicodeScalar($0)! } self.flags = flags self.loc = SourceLoc(file, line, comment: "test data") } } public var utfTests: [UTFTest] = [] // // Empty sequence. // utfTests.append( UTFTest( string: "", utf8: [], utf16: [], scalars: [])) // // 1-byte sequences. // // U+0000 NULL utfTests.append( UTFTest( string: "\u{0000}", utf8: [ 0x00 ], utf16: [ 0x00 ], scalars: [ 0x00 ])) // U+0041 LATIN CAPITAL LETTER A utfTests.append( UTFTest( string: "A", utf8: [ 0x41 ], utf16: [ 0x41 ], scalars: [ 0x41 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B utfTests.append( UTFTest( string: "AB", utf8: [ 0x41, 0x42 ], utf16: [ 0x41, 0x42 ], scalars: [ 0x41, 0x42 ])) // U+0061 LATIN SMALL LETTER A // U+0062 LATIN SMALL LETTER B // U+0063 LATIN SMALL LETTER C utfTests.append( UTFTest( string: "ABC", utf8: [ 0x41, 0x42, 0x43 ], utf16: [ 0x41, 0x42, 0x43 ], scalars: [ 0x41, 0x42, 0x43 ])) // U+0000 NULL // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0000 NULL utfTests.append( UTFTest( string: "\u{0000}AB\u{0000}", utf8: [ 0x00, 0x41, 0x42, 0x00 ], utf16: [ 0x00, 0x41, 0x42, 0x00 ], scalars: [ 0x00, 0x41, 0x42, 0x00 ])) // U+007F DELETE utfTests.append( UTFTest( string: "\u{007F}", utf8: [ 0x7F ], utf16: [ 0x7F ], scalars: [ 0x7F ])) // // 2-byte sequences. // // U+0283 LATIN SMALL LETTER ESH utfTests.append( UTFTest( string: "\u{0283}", utf8: [ 0xCA, 0x83 ], utf16: [ 0x0283 ], scalars: [ 0x0283 ])) // U+03BA GREEK SMALL LETTER KAPPA // U+1F79 GREEK SMALL LETTER OMICRON WITH OXIA // U+03C3 GREEK SMALL LETTER SIGMA // U+03BC GREEK SMALL LETTER MU // U+03B5 GREEK SMALL LETTER EPSILON utfTests.append( UTFTest( string: "\u{03BA}\u{1F79}\u{03C3}\u{03BC}\u{03B5}", utf8: [ 0xCE, 0xBA, 0xE1, 0xBD, 0xB9, 0xCF, 0x83, 0xCE, 0xBC, 0xCE, 0xB5 ], utf16: [ 0x03BA, 0x1F79, 0x03C3, 0x03BC, 0x03B5 ], scalars: [ 0x03BA, 0x1F79, 0x03C3, 0x03BC, 0x03B5 ])) // U+0430 CYRILLIC SMALL LETTER A // U+0431 CYRILLIC SMALL LETTER BE // U+0432 CYRILLIC SMALL LETTER VE utfTests.append( UTFTest( string: "\u{0430}\u{0431}\u{0432}", utf8: [ 0xD0, 0xB0, 0xD0, 0xB1, 0xD0, 0xB2 ], utf16: [ 0x0430, 0x0431, 0x0432 ], scalars: [ 0x0430, 0x0431, 0x0432 ])) // // 3-byte sequences. // // U+4F8B CJK UNIFIED IDEOGRAPH-4F8B // U+6587 CJK UNIFIED IDEOGRAPH-6587 utfTests.append( UTFTest( string: "\u{4F8b}\u{6587}", utf8: [ 0xE4, 0xBE, 0x8B, 0xE6, 0x96, 0x87 ], utf16: [ 0x4F8B, 0x6587 ], scalars: [ 0x4F8B, 0x6587 ])) // U+D55C HANGUL SYLLABLE HAN // U+AE00 HANGUL SYLLABLE GEUL utfTests.append( UTFTest( string: "\u{d55c}\u{ae00}", utf8: [ 0xED, 0x95, 0x9C, 0xEA, 0xB8, 0x80 ], utf16: [ 0xD55C, 0xAE00 ], scalars: [ 0xD55C, 0xAE00 ])) // U+1112 HANGUL CHOSEONG HIEUH // U+1161 HANGUL JUNGSEONG A // U+11AB HANGUL JONGSEONG NIEUN // U+1100 HANGUL CHOSEONG KIYEOK // U+1173 HANGUL JUNGSEONG EU // U+11AF HANGUL JONGSEONG RIEUL utfTests.append( UTFTest( string: "\u{1112}\u{1161}\u{11ab}\u{1100}\u{1173}\u{11af}", utf8: [ 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xA1, 0xE1, 0x86, 0xAB, 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xB3, 0xE1, 0x86, 0xAF ], utf16: [ 0x1112, 0x1161, 0x11AB, 0x1100, 0x1173, 0x11AF ], scalars: [ 0x1112, 0x1161, 0x11AB, 0x1100, 0x1173, 0x11AF ])) // U+3042 HIRAGANA LETTER A // U+3044 HIRAGANA LETTER I // U+3046 HIRAGANA LETTER U // U+3048 HIRAGANA LETTER E // U+304A HIRAGANA LETTER O utfTests.append( UTFTest( string: "\u{3042}\u{3044}\u{3046}\u{3048}\u{304a}", utf8: [ 0xE3, 0x81, 0x82, 0xE3, 0x81, 0x84, 0xE3, 0x81, 0x86, 0xE3, 0x81, 0x88, 0xE3, 0x81, 0x8A ], utf16: [ 0x3042, 0x3044, 0x3046, 0x3048, 0x304A ], scalars: [ 0x3042, 0x3044, 0x3046, 0x3048, 0x304A ])) // U+D7FF (unassigned) utfTests.append( UTFTest( string: "\u{D7FF}", utf8: [ 0xED, 0x9F, 0xBF ], utf16: [ 0xD7FF ], scalars: [ 0xD7FF ])) // U+E000 (private use) utfTests.append( UTFTest( string: "\u{E000}", utf8: [ 0xEE, 0x80, 0x80 ], utf16: [ 0xE000 ], scalars: [ 0xE000 ])) // U+FFFD REPLACEMENT CHARACTER utfTests.append( UTFTest( string: "\u{FFFD}", utf8: [ 0xEF, 0xBF, 0xBD ], utf16: [ 0xFFFD ], scalars: [ 0xFFFD ])) // U+FFFF (noncharacter) utfTests.append( UTFTest( string: "\u{FFFF}", utf8: [ 0xEF, 0xBF, 0xBF ], utf16: [ 0xFFFF ], scalars: [ 0xFFFF ])) // // 4-byte sequences. // // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "\u{1F425}", utf8: [ 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0xD83D, 0xDC25 ], scalars: [ 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "A\u{1F425}", utf8: [ 0x41, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "AB\u{1F425}", utf8: [ 0x41, 0x42, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABC\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCD\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+0045 LATIN CAPITAL LETTER E // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCDE\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+0045 LATIN CAPITAL LETTER E // U+0046 LATIN CAPITAL LETTER F // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCDEF\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+0045 LATIN CAPITAL LETTER E // U+0046 LATIN CAPITAL LETTER F // U+0047 LATIN CAPITAL LETTER G // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCDEFG\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+0045 LATIN CAPITAL LETTER E // U+0046 LATIN CAPITAL LETTER F // U+0047 LATIN CAPITAL LETTER G // U+0048 LATIN CAPITAL LETTER H // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCDEFGH\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x0001_F425 ])) // U+0041 LATIN CAPITAL LETTER A // U+0042 LATIN CAPITAL LETTER B // U+0043 LATIN CAPITAL LETTER C // U+0044 LATIN CAPITAL LETTER D // U+0045 LATIN CAPITAL LETTER E // U+0046 LATIN CAPITAL LETTER F // U+0047 LATIN CAPITAL LETTER G // U+0048 LATIN CAPITAL LETTER H // U+0049 LATIN CAPITAL LETTER I // U+1F425 FRONT-FACING BABY CHICK utfTests.append( UTFTest( string: "ABCDEFGHI\u{1F425}", utf8: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xF0, 0x9F, 0x90, 0xA5 ], utf16: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xD83D, 0xDC25 ], scalars: [ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x0001_F425 ])) // U+10000 LINEAR B SYLLABLE B008 A utfTests.append( UTFTest( string: "\u{10000}", utf8: [ 0xF0, 0x90, 0x80, 0x80 ], utf16: [ 0xD800, 0xDC00 ], scalars: [ 0x0001_0000 ])) // U+10100 AEGEAN WORD SEPARATOR LINE utfTests.append( UTFTest( string: "\u{10100}", utf8: [ 0xF0, 0x90, 0x84, 0x80 ], utf16: [ 0xD800, 0xDD00 ], scalars: [ 0x0001_0100 ])) // U+103FF (unassigned) utfTests.append( UTFTest( string: "\u{103FF}", utf8: [ 0xF0, 0x90, 0x8F, 0xBF ], utf16: [ 0xD800, 0xDFFF ], scalars: [ 0x0001_03FF ])) // U+E0000 (unassigned) utfTests.append( UTFTest( string: "\u{E0000}", utf8: [ 0xF3, 0xA0, 0x80, 0x80 ], utf16: [ 0xDB40, 0xDC00 ], scalars: [ 0x000E_0000 ])) // U+E0100 VARIATION SELECTOR-17 utfTests.append( UTFTest( string: "\u{E0100}", utf8: [ 0xF3, 0xA0, 0x84, 0x80 ], utf16: [ 0xDB40, 0xDD00 ], scalars: [ 0x000E_0100 ])) // U+E03FF (unassigned) utfTests.append( UTFTest( string: "\u{E03FF}", utf8: [ 0xF3, 0xA0, 0x8F, 0xBF ], utf16: [ 0xDB40, 0xDFFF ], scalars: [ 0x000E_03FF ])) // U+10FC00 (private use) utfTests.append( UTFTest( string: "\u{10FC00}", utf8: [ 0xF4, 0x8F, 0xB0, 0x80 ], utf16: [ 0xDBFF, 0xDC00 ], scalars: [ 0x0010_FC00 ])) // U+10FD00 (private use) utfTests.append( UTFTest( string: "\u{10FD00}", utf8: [ 0xF4, 0x8F, 0xB4, 0x80 ], utf16: [ 0xDBFF, 0xDD00 ], scalars: [ 0x0010_FD00 ])) // U+10FFFF (private use, noncharacter) utfTests.append( UTFTest( string: "\u{10FFFF}", utf8: [ 0xF4, 0x8F, 0xBF, 0xBF ], utf16: [ 0xDBFF, 0xDFFF ], scalars: [ 0x0010_FFFF ])) //===----------------------------------------------------------------------===// UTF8Decoder.test("SmokeTest").forEach(in: utfTests) { test in expectTrue( checkDecodeUTF8(test.utf32, [], test.utf8), stackTrace: test.loc.withCurrentLoc()) return () } UTF8Decoder.test("FirstPossibleSequence") { // // First possible sequence of a certain length // // U+0000 NULL expectTrue(checkDecodeUTF8([ 0x0000 ], [], [ 0x00 ])) // U+0080 PADDING CHARACTER expectTrue(checkDecodeUTF8([ 0x0080 ], [], [ 0xc2, 0x80 ])) // U+0800 SAMARITAN LETTER ALAF expectTrue(checkDecodeUTF8( [ 0x0800 ], [], [ 0xe0, 0xa0, 0x80 ])) // U+10000 LINEAR B SYLLABLE B008 A expectTrue(checkDecodeUTF8( [ 0x10000 ], [], [ 0xf0, 0x90, 0x80, 0x80 ])) // U+200000 (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x88, 0x80, 0x80, 0x80 ])) // U+4000000 (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x84, 0x80, 0x80, 0x80, 0x80 ])) } UTF8Decoder.test("LastPossibleSequence") { // // Last possible sequence of a certain length // // U+007F DELETE expectTrue(checkDecodeUTF8([ 0x007f ], [], [ 0x7f ])) // U+07FF (unassigned) expectTrue(checkDecodeUTF8([ 0x07ff ], [], [ 0xdf, 0xbf ])) // U+FFFF (noncharacter) expectTrue(checkDecodeUTF8( [ 0xffff ], [], [ 0xef, 0xbf, 0xbf ])) // U+1FFFFF (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf7, 0xbf, 0xbf, 0xbf ])) // U+3FFFFFF (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfb, 0xbf, 0xbf, 0xbf, 0xbf ])) // U+7FFFFFFF (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf ])) } UTF8Decoder.test("CodeSpaceBoundaryConditions") { // // Other boundary conditions // // U+D7FF (unassigned) expectTrue(checkDecodeUTF8([ 0xd7ff ], [], [ 0xed, 0x9f, 0xbf ])) // U+E000 (private use) expectTrue(checkDecodeUTF8([ 0xe000 ], [], [ 0xee, 0x80, 0x80 ])) // U+FFFD REPLACEMENT CHARACTER expectTrue(checkDecodeUTF8([ 0xfffd ], [], [ 0xef, 0xbf, 0xbd ])) // U+10FFFF (noncharacter) expectTrue(checkDecodeUTF8([ 0x10ffff ], [], [ 0xf4, 0x8f, 0xbf, 0xbf ])) // U+110000 (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf4, 0x90, 0x80, 0x80 ])) } UTF8Decoder.test("UnexpectedContinuationBytes") { // // Unexpected continuation bytes // // A sequence of unexpected continuation bytes that don't follow a first // byte, every byte is a maximal subpart. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0x80, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0x80, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xbf, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0x80, 0xbf, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0x80, 0xbf, 0x80, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0x80, 0xbf, 0x82, 0xbf, 0xaa ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xaa, 0xb0, 0xbb, 0xbf, 0xaa, 0xa0 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xaa, 0xb0, 0xbb, 0xbf, 0xaa, 0xa0, 0x8f ])) // All continuation bytes (0x80--0xbf). expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf ])) } UTF8Decoder.test("LonelyStartBytes") { // // Lonely start bytes // // Start bytes of 2-byte sequences (0xc0--0xdf). expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xc0, 0x20, 0xc1, 0x20, 0xc2, 0x20, 0xc3, 0x20, 0xc4, 0x20, 0xc5, 0x20, 0xc6, 0x20, 0xc7, 0x20, 0xc8, 0x20, 0xc9, 0x20, 0xca, 0x20, 0xcb, 0x20, 0xcc, 0x20, 0xcd, 0x20, 0xce, 0x20, 0xcf, 0x20, 0xd0, 0x20, 0xd1, 0x20, 0xd2, 0x20, 0xd3, 0x20, 0xd4, 0x20, 0xd5, 0x20, 0xd6, 0x20, 0xd7, 0x20, 0xd8, 0x20, 0xd9, 0x20, 0xda, 0x20, 0xdb, 0x20, 0xdc, 0x20, 0xdd, 0x20, 0xde, 0x20, 0xdf, 0x20 ])) // Start bytes of 3-byte sequences (0xe0--0xef). expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xe0, 0x20, 0xe1, 0x20, 0xe2, 0x20, 0xe3, 0x20, 0xe4, 0x20, 0xe5, 0x20, 0xe6, 0x20, 0xe7, 0x20, 0xe8, 0x20, 0xe9, 0x20, 0xea, 0x20, 0xeb, 0x20, 0xec, 0x20, 0xed, 0x20, 0xee, 0x20, 0xef, 0x20 ])) // Start bytes of 4-byte sequences (0xf0--0xf7). expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xf0, 0x20, 0xf1, 0x20, 0xf2, 0x20, 0xf3, 0x20, 0xf4, 0x20, 0xf5, 0x20, 0xf6, 0x20, 0xf7, 0x20 ])) // Start bytes of 5-byte sequences (0xf8--0xfb). expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0xf9, 0xfa, 0xfb ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xf8, 0x20, 0xf9, 0x20, 0xfa, 0x20, 0xfb, 0x20 ])) // Start bytes of 6-byte sequences (0xfc--0xfd). expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0xfd ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xfc, 0x20, 0xfd, 0x20 ])) } UTF8Decoder.test("InvalidStartBytes") { // // Other bytes (0xc0--0xc1, 0xfe--0xff). // expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc1 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfe ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xff ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xc0, 0xc1, 0xfe, 0xff ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfe, 0xfe, 0xff, 0xff ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfe, 0x80, 0x80, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xff, 0x80, 0x80, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020 ], [ 0xc0, 0x20, 0xc1, 0x20, 0xfe, 0x20, 0xff, 0x20 ])) } UTF8Decoder.test("MissingContinuationBytes") { // // Sequences with one continuation byte missing // expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc2 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xdf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xc2, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xdf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0, 0xa0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe0, 0xa0, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe0, 0xbf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe1, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xec, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xe1, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xec, 0xbf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed, 0x9f ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xed, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xed, 0x9f, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xee, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xef, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xee, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xef, 0xbf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0x90, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf0, 0x90, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf0, 0xbf, 0xbf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf1, 0x80, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf3, 0xbf, 0xbf, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x8f, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf4, 0x80, 0x80, 0x41 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0x0041 ], [ 0xf4, 0x8f, 0xbf, 0x41 ])) // Overlong sequences with one trailing byte missing. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xc1 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xe0, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xe0, 0x9f ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x8f, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x80, 0x80, 0x80, 0x80 ])) // Sequences that represent surrogates with one trailing byte missing. // High-surrogates expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xa0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xac ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xaf ])) // Low-surrogates expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xb0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xb4 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xed, 0xbf ])) // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+1100xx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf4, 0x90, 0x80 ])) // U+13FBxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf4, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf5, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf6, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf7, 0x80, 0x80 ])) // U+1FFBxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf7, 0xbf, 0xbf ])) // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+2000xx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x88, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0xbf, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf9, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfa, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfb, 0x80, 0x80, 0x80 ])) // U+3FFFFxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfb, 0xbf, 0xbf, 0xbf ])) // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10uzzzzz 10zzzyyyy 10yyyyxx 10xxxxxx // U+40000xx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x84, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0xbf, 0xbf, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0x80, 0x80, 0x80, 0x80 ])) // U+7FFFFFxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0xbf, 0xbf, 0xbf, 0xbf ])) // // Sequences with two continuation bytes missing // expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0x90 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4, 0x8f ])) // Overlong sequences with two trailing byte missing. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xe0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf0, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf0, 0x8f ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x80, 0x80, 0x80 ])) // Sequences that represent surrogates with two trailing bytes missing. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xed ])) // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+110yxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf4, 0x90 ])) // U+13Fyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf4, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf5, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf6, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf7, 0x80 ])) // U+1FFyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf7, 0xbf ])) // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+200yxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x88, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xf9, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfa, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfb, 0x80, 0x80 ])) // U+3FFFyxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfb, 0xbf, 0xbf ])) // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+4000yxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x84, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0xbf, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0x80, 0x80, 0x80 ])) // U+7FFFFyxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0xbf, 0xbf, 0xbf ])) // // Sequences with three continuation bytes missing // expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf1 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf2 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf3 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf4 ])) // Broken overlong sequences. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf0 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x80, 0x80 ])) // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+14yyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf5 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf6 ])) // U+1Cyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf7 ])) // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+20yyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0x88 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf8, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xf9, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfa, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfb, 0x80 ])) // U+3FCyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfb, 0xbf ])) // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+400yyxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x84, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0x80, 0x80 ])) // U+7FFCyyxx (invalid) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xfd, 0xbf, 0xbf ])) // // Sequences with four continuation bytes missing // // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf8 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf9 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfa ])) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfb ])) // U+3zyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfb ])) // Broken overlong sequences. expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xf8 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0x80 ])) // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzzyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0x84 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfc, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfd, 0x80 ])) // U+7Fzzyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xfd, 0xbf ])) // // Sequences with five continuation bytes missing // // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzzyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfc ])) // U+uuzzyyxx (invalid) expectTrue(checkDecodeUTF8([], [ 0xfffd ], [ 0xfd ])) // // Consecutive sequences with trailing bytes missing // expectTrue(checkDecodeUTF8( [], [ 0xfffd, /**/ 0xfffd, 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, /**/ 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xc0, /**/ 0xe0, 0x80, /**/ 0xf0, 0x80, 0x80, 0xf8, 0x80, 0x80, 0x80, 0xfc, 0x80, 0x80, 0x80, 0x80, 0xdf, /**/ 0xef, 0xbf, /**/ 0xf7, 0xbf, 0xbf, 0xfb, 0xbf, 0xbf, 0xbf, 0xfd, 0xbf, 0xbf, 0xbf, 0xbf ])) } UTF8Decoder.test("OverlongSequences") { // // Overlong UTF-8 sequences // // U+002F SOLIDUS expectTrue(checkDecodeUTF8([ 0x002f ], [], [ 0x2f ])) // Overlong sequences of the above. expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0xaf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xe0, 0x80, 0xaf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x80, 0x80, 0xaf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x80, 0x80, 0x80, 0xaf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x80, 0x80, 0x80, 0x80, 0xaf ])) // U+0000 NULL expectTrue(checkDecodeUTF8([ 0x0000 ], [], [ 0x00 ])) // Overlong sequences of the above. expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xe0, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x80, 0x80, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x80, 0x80, 0x80, 0x80, 0x80 ])) // Other overlong and ill-formed sequences. expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc0, 0xbf ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc1, 0x80 ])) expectTrue(checkDecodeUTF8([], [ 0xfffd, 0xfffd ], [ 0xc1, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xe0, 0x9f, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xa0, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x8f, 0x80, 0x80 ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf0, 0x8f, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xf8, 0x87, 0xbf, 0xbf, 0xbf ])) expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xfc, 0x83, 0xbf, 0xbf, 0xbf, 0xbf ])) } UTF8Decoder.test("IsolatedSurrogates") { // Unicode 6.3.0: // // D71. High-surrogate code point: A Unicode code point in the range // U+D800 to U+DBFF. // // D73. Low-surrogate code point: A Unicode code point in the range // U+DC00 to U+DFFF. // Note: U+E0100 is <DB40 DD00> in UTF-16. // High-surrogates // U+D800 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xa0, 0x80 ])) expectTrue(checkDecodeUTF8( [ 0x0041 ], [ 0xfffd, 0xfffd, 0xfffd, 0x0041 ], [ 0x41, 0xed, 0xa0, 0x80, 0x41 ])) // U+DB40 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xac, 0xa0 ])) // U+DBFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xaf, 0xbf ])) // Low-surrogates // U+DC00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xb0, 0x80 ])) // U+DD00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xb4, 0x80 ])) // U+DFFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xbf, 0xbf ])) } UTF8Decoder.test("SurrogatePairs") { // Surrogate pairs // U+D800 U+DC00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80 ])) // U+D800 U+DD00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xa0, 0x80, 0xed, 0xb4, 0x80 ])) // U+D800 U+DFFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf ])) // U+DB40 U+DC00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xac, 0xa0, 0xed, 0xb0, 0x80 ])) // U+DB40 U+DD00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xac, 0xa0, 0xed, 0xb4, 0x80 ])) // U+DB40 U+DFFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xac, 0xa0, 0xed, 0xbf, 0xbf ])) // U+DBFF U+DC00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80 ])) // U+DBFF U+DD00 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xaf, 0xbf, 0xed, 0xb4, 0x80 ])) // U+DBFF U+DFFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf ])) } UTF8Decoder.test("Noncharacters") { // // Noncharacters // // Unicode 6.3.0: // // D14. Noncharacter: A code point that is permanently reserved for // internal use and that should never be interchanged. Noncharacters // consist of the values U+nFFFE and U+nFFFF (where n is from 0 to 1016) // and the values U+FDD0..U+FDEF. // U+FFFE expectTrue(checkDecodeUTF8([ 0xfffe ], [], [ 0xef, 0xbf, 0xbe ])) // U+FFFF expectTrue(checkDecodeUTF8([ 0xffff ], [], [ 0xef, 0xbf, 0xbf ])) // U+1FFFE expectTrue(checkDecodeUTF8([ 0x1fffe ], [], [ 0xf0, 0x9f, 0xbf, 0xbe ])) // U+1FFFF expectTrue(checkDecodeUTF8([ 0x1ffff ], [], [ 0xf0, 0x9f, 0xbf, 0xbf ])) // U+2FFFE expectTrue(checkDecodeUTF8([ 0x2fffe ], [], [ 0xf0, 0xaf, 0xbf, 0xbe ])) // U+2FFFF expectTrue(checkDecodeUTF8([ 0x2ffff ], [], [ 0xf0, 0xaf, 0xbf, 0xbf ])) // U+3FFFE expectTrue(checkDecodeUTF8([ 0x3fffe ], [], [ 0xf0, 0xbf, 0xbf, 0xbe ])) // U+3FFFF expectTrue(checkDecodeUTF8([ 0x3ffff ], [], [ 0xf0, 0xbf, 0xbf, 0xbf ])) // U+4FFFE expectTrue(checkDecodeUTF8([ 0x4fffe ], [], [ 0xf1, 0x8f, 0xbf, 0xbe ])) // U+4FFFF expectTrue(checkDecodeUTF8([ 0x4ffff ], [], [ 0xf1, 0x8f, 0xbf, 0xbf ])) // U+5FFFE expectTrue(checkDecodeUTF8([ 0x5fffe ], [], [ 0xf1, 0x9f, 0xbf, 0xbe ])) // U+5FFFF expectTrue(checkDecodeUTF8([ 0x5ffff ], [], [ 0xf1, 0x9f, 0xbf, 0xbf ])) // U+6FFFE expectTrue(checkDecodeUTF8([ 0x6fffe ], [], [ 0xf1, 0xaf, 0xbf, 0xbe ])) // U+6FFFF expectTrue(checkDecodeUTF8([ 0x6ffff ], [], [ 0xf1, 0xaf, 0xbf, 0xbf ])) // U+7FFFE expectTrue(checkDecodeUTF8([ 0x7fffe ], [], [ 0xf1, 0xbf, 0xbf, 0xbe ])) // U+7FFFF expectTrue(checkDecodeUTF8([ 0x7ffff ], [], [ 0xf1, 0xbf, 0xbf, 0xbf ])) // U+8FFFE expectTrue(checkDecodeUTF8([ 0x8fffe ], [], [ 0xf2, 0x8f, 0xbf, 0xbe ])) // U+8FFFF expectTrue(checkDecodeUTF8([ 0x8ffff ], [], [ 0xf2, 0x8f, 0xbf, 0xbf ])) // U+9FFFE expectTrue(checkDecodeUTF8([ 0x9fffe ], [], [ 0xf2, 0x9f, 0xbf, 0xbe ])) // U+9FFFF expectTrue(checkDecodeUTF8([ 0x9ffff ], [], [ 0xf2, 0x9f, 0xbf, 0xbf ])) // U+AFFFE expectTrue(checkDecodeUTF8([ 0xafffe ], [], [ 0xf2, 0xaf, 0xbf, 0xbe ])) // U+AFFFF expectTrue(checkDecodeUTF8([ 0xaffff ], [], [ 0xf2, 0xaf, 0xbf, 0xbf ])) // U+BFFFE expectTrue(checkDecodeUTF8([ 0xbfffe ], [], [ 0xf2, 0xbf, 0xbf, 0xbe ])) // U+BFFFF expectTrue(checkDecodeUTF8([ 0xbffff ], [], [ 0xf2, 0xbf, 0xbf, 0xbf ])) // U+CFFFE expectTrue(checkDecodeUTF8([ 0xcfffe ], [], [ 0xf3, 0x8f, 0xbf, 0xbe ])) // U+CFFFF expectTrue(checkDecodeUTF8([ 0xcfffF ], [], [ 0xf3, 0x8f, 0xbf, 0xbf ])) // U+DFFFE expectTrue(checkDecodeUTF8([ 0xdfffe ], [], [ 0xf3, 0x9f, 0xbf, 0xbe ])) // U+DFFFF expectTrue(checkDecodeUTF8([ 0xdffff ], [], [ 0xf3, 0x9f, 0xbf, 0xbf ])) // U+EFFFE expectTrue(checkDecodeUTF8([ 0xefffe ], [], [ 0xf3, 0xaf, 0xbf, 0xbe ])) // U+EFFFF expectTrue(checkDecodeUTF8([ 0xeffff ], [], [ 0xf3, 0xaf, 0xbf, 0xbf ])) // U+FFFFE expectTrue(checkDecodeUTF8([ 0xffffe ], [], [ 0xf3, 0xbf, 0xbf, 0xbe ])) // U+FFFFF expectTrue(checkDecodeUTF8([ 0xfffff ], [], [ 0xf3, 0xbf, 0xbf, 0xbf ])) // U+10FFFE expectTrue(checkDecodeUTF8([ 0x10fffe ], [], [ 0xf4, 0x8f, 0xbf, 0xbe ])) // U+10FFFF expectTrue(checkDecodeUTF8([ 0x10ffff ], [], [ 0xf4, 0x8f, 0xbf, 0xbf ])) // U+FDD0 expectTrue(checkDecodeUTF8([ 0xfdd0 ], [], [ 0xef, 0xb7, 0x90 ])) // U+FDD1 expectTrue(checkDecodeUTF8([ 0xfdd1 ], [], [ 0xef, 0xb7, 0x91 ])) // U+FDD2 expectTrue(checkDecodeUTF8([ 0xfdd2 ], [], [ 0xef, 0xb7, 0x92 ])) // U+FDD3 expectTrue(checkDecodeUTF8([ 0xfdd3 ], [], [ 0xef, 0xb7, 0x93 ])) // U+FDD4 expectTrue(checkDecodeUTF8([ 0xfdd4 ], [], [ 0xef, 0xb7, 0x94 ])) // U+FDD5 expectTrue(checkDecodeUTF8([ 0xfdd5 ], [], [ 0xef, 0xb7, 0x95 ])) // U+FDD6 expectTrue(checkDecodeUTF8([ 0xfdd6 ], [], [ 0xef, 0xb7, 0x96 ])) // U+FDD7 expectTrue(checkDecodeUTF8([ 0xfdd7 ], [], [ 0xef, 0xb7, 0x97 ])) // U+FDD8 expectTrue(checkDecodeUTF8([ 0xfdd8 ], [], [ 0xef, 0xb7, 0x98 ])) // U+FDD9 expectTrue(checkDecodeUTF8([ 0xfdd9 ], [], [ 0xef, 0xb7, 0x99 ])) // U+FDDA expectTrue(checkDecodeUTF8([ 0xfdda ], [], [ 0xef, 0xb7, 0x9a ])) // U+FDDB expectTrue(checkDecodeUTF8([ 0xfddb ], [], [ 0xef, 0xb7, 0x9b ])) // U+FDDC expectTrue(checkDecodeUTF8([ 0xfddc ], [], [ 0xef, 0xb7, 0x9c ])) // U+FDDD expectTrue(checkDecodeUTF8([ 0xfddd ], [], [ 0xef, 0xb7, 0x9d ])) // U+FDDE expectTrue(checkDecodeUTF8([ 0xfdde ], [], [ 0xef, 0xb7, 0x9e ])) // U+FDDF expectTrue(checkDecodeUTF8([ 0xfddf ], [], [ 0xef, 0xb7, 0x9f ])) // U+FDE0 expectTrue(checkDecodeUTF8([ 0xfde0 ], [], [ 0xef, 0xb7, 0xa0 ])) // U+FDE1 expectTrue(checkDecodeUTF8([ 0xfde1 ], [], [ 0xef, 0xb7, 0xa1 ])) // U+FDE2 expectTrue(checkDecodeUTF8([ 0xfde2 ], [], [ 0xef, 0xb7, 0xa2 ])) // U+FDE3 expectTrue(checkDecodeUTF8([ 0xfde3 ], [], [ 0xef, 0xb7, 0xa3 ])) // U+FDE4 expectTrue(checkDecodeUTF8([ 0xfde4 ], [], [ 0xef, 0xb7, 0xa4 ])) // U+FDE5 expectTrue(checkDecodeUTF8([ 0xfde5 ], [], [ 0xef, 0xb7, 0xa5 ])) // U+FDE6 expectTrue(checkDecodeUTF8([ 0xfde6 ], [], [ 0xef, 0xb7, 0xa6 ])) // U+FDE7 expectTrue(checkDecodeUTF8([ 0xfde7 ], [], [ 0xef, 0xb7, 0xa7 ])) // U+FDE8 expectTrue(checkDecodeUTF8([ 0xfde8 ], [], [ 0xef, 0xb7, 0xa8 ])) // U+FDE9 expectTrue(checkDecodeUTF8([ 0xfde9 ], [], [ 0xef, 0xb7, 0xa9 ])) // U+FDEA expectTrue(checkDecodeUTF8([ 0xfdea ], [], [ 0xef, 0xb7, 0xaa ])) // U+FDEB expectTrue(checkDecodeUTF8([ 0xfdeb ], [], [ 0xef, 0xb7, 0xab ])) // U+FDEC expectTrue(checkDecodeUTF8([ 0xfdec ], [], [ 0xef, 0xb7, 0xac ])) // U+FDED expectTrue(checkDecodeUTF8([ 0xfded ], [], [ 0xef, 0xb7, 0xad ])) // U+FDEE expectTrue(checkDecodeUTF8([ 0xfdee ], [], [ 0xef, 0xb7, 0xae ])) // U+FDEF expectTrue(checkDecodeUTF8([ 0xfdef ], [], [ 0xef, 0xb7, 0xaf ])) // U+FDF0 expectTrue(checkDecodeUTF8([ 0xfdf0 ], [], [ 0xef, 0xb7, 0xb0 ])) // U+FDF1 expectTrue(checkDecodeUTF8([ 0xfdf1 ], [], [ 0xef, 0xb7, 0xb1 ])) // U+FDF2 expectTrue(checkDecodeUTF8([ 0xfdf2 ], [], [ 0xef, 0xb7, 0xb2 ])) // U+FDF3 expectTrue(checkDecodeUTF8([ 0xfdf3 ], [], [ 0xef, 0xb7, 0xb3 ])) // U+FDF4 expectTrue(checkDecodeUTF8([ 0xfdf4 ], [], [ 0xef, 0xb7, 0xb4 ])) // U+FDF5 expectTrue(checkDecodeUTF8([ 0xfdf5 ], [], [ 0xef, 0xb7, 0xb5 ])) // U+FDF6 expectTrue(checkDecodeUTF8([ 0xfdf6 ], [], [ 0xef, 0xb7, 0xb6 ])) // U+FDF7 expectTrue(checkDecodeUTF8([ 0xfdf7 ], [], [ 0xef, 0xb7, 0xb7 ])) // U+FDF8 expectTrue(checkDecodeUTF8([ 0xfdf8 ], [], [ 0xef, 0xb7, 0xb8 ])) // U+FDF9 expectTrue(checkDecodeUTF8([ 0xfdf9 ], [], [ 0xef, 0xb7, 0xb9 ])) // U+FDFA expectTrue(checkDecodeUTF8([ 0xfdfa ], [], [ 0xef, 0xb7, 0xba ])) // U+FDFB expectTrue(checkDecodeUTF8([ 0xfdfb ], [], [ 0xef, 0xb7, 0xbb ])) // U+FDFC expectTrue(checkDecodeUTF8([ 0xfdfc ], [], [ 0xef, 0xb7, 0xbc ])) // U+FDFD expectTrue(checkDecodeUTF8([ 0xfdfd ], [], [ 0xef, 0xb7, 0xbd ])) // U+FDFE expectTrue(checkDecodeUTF8([ 0xfdfe ], [], [ 0xef, 0xb7, 0xbe ])) // U+FDFF expectTrue(checkDecodeUTF8([ 0xfdff ], [], [ 0xef, 0xb7, 0xbf ])) } var UTF16Decoder = TestSuite("UTF16Decoder") UTF16Decoder.test("UTF16.transcodedLength") { do { let u8: [UTF8.CodeUnit] = [ 0, 1, 2, 3, 4, 5 ] let (count, isASCII) = UTF16.transcodedLength( of: u8.makeIterator(), decodedAs: UTF8.self, repairingIllFormedSequences: false)! expectEqual(6, count) expectTrue(isASCII) } do { // "€" == U+20AC. let u8: [UTF8.CodeUnit] = [ 0xF0, 0xA4, 0xAD, 0xA2 ] let (count, isASCII) = UTF16.transcodedLength( of: u8.makeIterator(), decodedAs: UTF8.self, repairingIllFormedSequences: false)! expectEqual(2, count) expectFalse(isASCII) } do { let u16: [UTF16.CodeUnit] = [ 6, 7, 8, 9, 10, 11 ] let (count, isASCII) = UTF16.transcodedLength( of: u16.makeIterator(), decodedAs: UTF16.self, repairingIllFormedSequences: false)! expectEqual(6, count) expectTrue(isASCII) } } UTF16Decoder.test("Decoding1").forEach(in: utfTests) { test in expectTrue( checkDecodeUTF16( test.utf32, test.utf32RepairedTail, test.utf16), stackTrace: test.loc.withCurrentLoc()) return () } UTF16Decoder.test("Decoding2") { for (name, batch) in utf16Tests { print("Batch: \(name)") for test in batch { expectTrue(checkDecodeUTF16(test.scalarsHead, test.scalarsRepairedTail, test.encoded), stackTrace: test.loc.withCurrentLoc()) } } } public struct UTF16Test { public let scalarsHead: [UInt32] public let scalarsRepairedTail: [UInt32] public let encoded: [UInt16] public let loc: SourceLoc public init( _ scalarsHead: [UInt32], _ scalarsRepairedTail: [UInt32], _ encoded: [UInt16], file: String = #file, line: UInt = #line ) { self.scalarsHead = scalarsHead self.scalarsRepairedTail = scalarsRepairedTail self.encoded = encoded self.loc = SourceLoc(file, line, comment: "test data") } } public let utf16Tests = [ "Incomplete": [ // // Incomplete sequences that end right before EOF. // // U+D800 (high-surrogate) UTF16Test([], [ 0xFFFD ], [ 0xD800 ]), // U+D800 (high-surrogate) // U+D800 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xD800, 0xD800 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) UTF16Test([ 0x0041 ], [ 0xFFFD ], [ 0x0041, 0xD800 ]), // U+10000 LINEAR B SYLLABLE B008 A // U+D800 (high-surrogate) UTF16Test( [ 0x0001_0000 ], [ 0xFFFD ], [ 0xD800, 0xDC00, 0xD800 ]), // // Incomplete sequences with more code units following them. // // U+D800 (high-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test([], [ 0xFFFD, 0x0041 ], [ 0xD800, 0x0041 ]), // U+D800 (high-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [], [ 0xFFFD, 0x0001_0000 ], [ 0xD800, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0x0041 ], [ 0x0041, 0xD800, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xD800, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+DB40 (high-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0041 ], [ 0x0041, 0xD800, 0xDB40, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+DB40 (high-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xD800, 0xDB40, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+DB40 (high-surrogate) // U+DBFF (high-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0041 ], [ 0x0041, 0xD800, 0xDB40, 0xDBFF, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+D800 (high-surrogate) // U+DB40 (high-surrogate) // U+DBFF (high-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xD800, 0xDB40, 0xDBFF, 0xD800, 0xDC00 ]), ], "IllFormed": [ // // Low-surrogate right before EOF. // // U+DC00 (low-surrogate) UTF16Test([], [ 0xFFFD ], [ 0xDC00 ]), // U+DC00 (low-surrogate) // U+DC00 (low-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) UTF16Test([ 0x0041 ], [ 0xFFFD ], [ 0x0041, 0xDC00 ]), // U+10000 LINEAR B SYLLABLE B008 A // U+DC00 (low-surrogate) UTF16Test( [ 0x0001_0000 ], [ 0xFFFD ], [ 0xD800, 0xDC00, 0xDC00 ]), // // Low-surrogate with more code units following it. // // U+DC00 (low-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test([], [ 0xFFFD, 0x0041 ], [ 0xDC00, 0x0041 ]), // U+DC00 (low-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [], [ 0xFFFD, 0x0001_0000 ], [ 0xDC00, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0x0041 ], [ 0x0041, 0xDC00, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xDC00, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+DD00 (low-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0041 ], [ 0x0041, 0xDC00, 0xDD00, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+DD00 (low-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xDC00, 0xDD00, 0xD800, 0xDC00 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+DD00 (low-surrogate) // U+DFFF (low-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0041 ], [ 0x0041, 0xDC00, 0xDD00, 0xDFFF, 0x0041 ]), // U+0041 LATIN CAPITAL LETTER A // U+DC00 (low-surrogate) // U+DD00 (low-surrogate) // U+DFFF (low-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [ 0x0041 ], [ 0xFFFD, 0xFFFD, 0xFFFD, 0x0001_0000 ], [ 0x0041, 0xDC00, 0xDD00, 0xDFFF, 0xD800, 0xDC00 ]), // // Low-surrogate followed by high-surrogate. // // U+DC00 (low-surrogate) // U+D800 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xD800 ]), // U+DC00 (low-surrogate) // U+DB40 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDB40 ]), // U+DC00 (low-surrogate) // U+DBFF (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDC00, 0xDBFF ]), // U+DD00 (low-surrogate) // U+D800 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xD800 ]), // U+DD00 (low-surrogate) // U+DB40 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xDB40 ]), // U+DD00 (low-surrogate) // U+DBFF (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDD00, 0xDBFF ]), // U+DFFF (low-surrogate) // U+D800 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xD800 ]), // U+DFFF (low-surrogate) // U+DB40 (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xDB40 ]), // U+DFFF (low-surrogate) // U+DBFF (high-surrogate) UTF16Test([], [ 0xFFFD, 0xFFFD ], [ 0xDFFF, 0xDBFF ]), // U+DC00 (low-surrogate) // U+D800 (high-surrogate) // U+0041 LATIN CAPITAL LETTER A UTF16Test( [], [ 0xFFFD, 0xFFFD, 0x0041 ], [ 0xDC00, 0xD800, 0x0041 ]), // U+DC00 (low-surrogate) // U+D800 (high-surrogate) // U+10000 LINEAR B SYLLABLE B008 A UTF16Test( [], [ 0xFFFD, 0xFFFD, 0x10000 ], [ 0xDC00, 0xD800, 0xD800, 0xDC00 ]), ], ] runAllTests() #else //===--- benchmarking -----------------------------------------------------===// @inline(never) public func run_UTF8Decode(_ N: Int) { // 1-byte sequences // This test case is the longest as it's the most performance sensitive. let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program." // 2-byte sequences let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа." // 3-byte sequences let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。" // 4-byte sequences // Most commonly emoji, which are usually mixed with other text. let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭." let strings = [ascii, russian, japanese, emoji].map { Array($0.utf8) } func isEmpty(_ result: UnicodeDecodingResult) -> Bool { switch result { case .emptyInput: return true default: return false } } var total: UInt32 = 0 for _ in 1...200*N { for string in strings { #if BASELINE _ = transcode( string.makeIterator(), from: UTF8.self, to: UTF32.self, stoppingOnError: false ) { total = total &+ $0 } #else #if FORWARD var it = string.makeIterator() typealias D = UTF8.ForwardDecoder D.decode(&it, repairingIllFormedSequences: true) { total = total &+ $0.value } #elseif REVERSE var it = string.reversed().makeIterator() typealias D = UTF8.ReverseDecoder D.decode(&it, repairingIllFormedSequences: true) { total = total &+ $0.value } #elseif SEQUENCE for s in Unicode.DefaultScalarView(string, fromEncoding: UTF8.self) { total = total &+ s.value } #elseif COLLECTION let scalars = Unicode.DefaultScalarView(string, fromEncoding: UTF8.self) var i = scalars.startIndex while i != scalars.endIndex { total = total &+ scalars[i].value i = scalars.index(after: i) } #elseif REVERSE_COLLECTION let scalars = Unicode.DefaultScalarView(string, fromEncoding: UTF8.self) var i = scalars.endIndex while i != scalars.startIndex { i = scalars.index(before: i) total = total &+ scalars[i].value } #else Error_Unknown_Benchmark() #endif #endif } } if CommandLine.arguments.count > 1000 { print(total) } } run_UTF8Decode(10000) #endif
apache-2.0
shajrawi/swift
test/type/self.swift
2
4546
// RUN: %target-typecheck-verify-swift -swift-version 5 struct S0<T> { func foo(_ other: Self) { } } class C0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}} } enum E0<T> { func foo(_ other: Self) { } } // rdar://problem/21745221 struct X { typealias T = Int } extension X { struct Inner { } } extension X.Inner { func foo(_ other: Self) { } } // SR-695 class Mario { func getFriend() -> Self { return self } // expected-note{{overridden declaration is here}} func getEnemy() -> Mario { return self } } class SuperMario : Mario { override func getFriend() -> SuperMario { // expected-error{{cannot override a Self return type with a non-Self return type}} return SuperMario() } override func getEnemy() -> Self { return self } } final class FinalMario : Mario { override func getFriend() -> FinalMario { return FinalMario() } } // These references to Self are now possible (SE-0068) class A<T> { typealias _Self = Self // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} let b: Int required init(a: Int) { print("\(Self.self).\(#function)") Self.y() b = a } static func z(n: Self? = nil) { // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} print("\(Self.self).\(#function)") } class func y() { print("\(Self.self).\(#function)") Self.z() } func x() -> A? { print("\(Self.self).\(#function)") Self.y() Self.z() let _: Self = Self.init(a: 66) // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} return Self.init(a: 77) as? Self as? A // expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}} // expected-warning@-2 {{conditional downcast from 'Self?' to 'A<T>' is equivalent to an implicit conversion to an optional 'A<T>'}} } func copy() -> Self { let copy = Self.init(a: 11) return copy } var copied: Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} let copy = Self.init(a: 11) return copy } subscript (i: Int) -> Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} get { return Self.init(a: i) } set(newValue) { } } } class B: A<Int> { let a: Int required convenience init(a: Int) { print("\(Self.self).\(#function)") self.init() } init() { print("\(Self.self).\(#function)") Self.y() Self.z() a = 99 super.init(a: 88) } override class func y() { print("override \(Self.self).\(#function)") } override func copy() -> Self { let copy = super.copy() as! Self // supported return copy } override var copied: Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'B'?}} let copy = super.copied as! Self // unsupported return copy } } class C { required init() { } func f() { func g(_: Self) {} } func g() { _ = Self.init() as? Self // expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}} } } struct S2 { let x = 99 struct S3<T> { let x = 99 static func x() { Self.y() } func f() { func g(_: Self) {} } static func y() { print("HERE") } func foo(a: [Self]) -> Self? { Self.x() return Self.init() as? Self // expected-warning@-1 {{conditional cast from 'S2.S3<T>' to 'S2.S3<T>' always succeeds}} } } func copy() -> Self { let copy = Self.init() return copy } var copied: Self { let copy = Self.init() return copy } } extension S2 { static func x() { Self.y() } static func y() { print("HERE") } func f() { func g(_: Self) {} } func foo(a: [Self]) -> Self? { Self.x() return Self.init() as? Self // expected-warning@-1 {{conditional cast from 'S2' to 'S2' always succeeds}} } subscript (i: Int) -> Self { get { return Self.init() } set(newValue) { } } } enum E { static func f() { func g(_: Self) {} print("f()") } case e func h(h: Self) -> Self { Self.f() return .e } }
apache-2.0
BalestraPatrick/TweetsCounter
Carthage/Checkouts/Swifter/Sources/SwifterError.swift
2
1580
// // SwifterError.swift // Swifter // // Created by Andy Liang on 2016-08-11. // Copyright © 2016 Matt Donnelly. All rights reserved. // import Foundation public struct SwifterError: Error { public enum ErrorKind: CustomStringConvertible { case invalidAppOnlyBearerToken case responseError(code: Int) case invalidJSONResponse case badOAuthResponse case urlResponseError(status: Int, headers: [AnyHashable: Any], errorCode: Int) case jsonParseError case invalidGifData case invalidGifResponse public var description: String { switch self { case .invalidAppOnlyBearerToken: return "invalidAppOnlyBearerToken" case .invalidJSONResponse: return "invalidJSONResponse" case .responseError(let code): return "responseError(code: \(code))" case .badOAuthResponse: return "badOAuthResponse" case .urlResponseError(let code, let headers, let errorCode): return "urlResponseError(status: \(code), headers: \(headers), errorCode: \(errorCode)" case .jsonParseError: return "jsonParseError" case .invalidGifData: return "invalidGifData" case .invalidGifResponse: return "invalidGifResponse" } } } public var message: String public var kind: ErrorKind public var localizedDescription: String { return "[\(kind.description)] - \(message)" } }
mit
tad-iizuka/swift-sdk
Source/ConversationV1/Models/MessageResponse.swift
2
2391
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** A response from the Conversation service. */ public struct MessageResponse: JSONDecodable { /// The raw JSON object used to construct this model. public let json: [String: Any] /// The user input from the request. public let input: Input? /// Whether to return more than one intent. /// Included in the response only when sent with the request. public let alternateIntents: Bool? /// Information about the state of the conversation. public let context: Context /// An array of terms from the request that were identified as entities. /// The array is empty if no entities were identified. public let entities: [Entity] /// An array of terms from the request that were identified as intents. Each intent has an /// associated confidence. The list is sorted in descending order of confidence. If there are /// 10 or fewer intents then the sum of the confidence values is 100%. The array is empty if /// no intents were identified. public let intents: [Intent] /// An output object that includes the response to the user, /// the nodes that were hit, and messages from the log. public let output: Output /// Used internally to initialize a `MessageResponse` model from JSON. public init(json: JSON) throws { self.json = try json.getDictionaryObject() input = try? json.decode(at: "input") alternateIntents = try? json.getBool(at: "alternate_intents") context = try json.decode(at: "context") entities = try json.decodedArray(at: "entities", type: Entity.self) intents = try json.decodedArray(at: "intents", type: Intent.self) output = try json.decode(at: "output") } }
apache-2.0
GuiminChu/JianshuExamples
CustomPresentationViewController/CustomPresentationViewController/CustomPresentationController/CustomPresentationController.swift
2
796
// // CustomPresentationController.swift // CustomPresentationViewController // // Created by Chu Guimin on 16/9/8. // Copyright © 2016年 Chu Guimin. All rights reserved. // import UIKit class CustomPresentationController: UIPresentationController { override func presentationTransitionWillBegin() { print("willBegin") presentedViewController.transitionCoordinator()?.animateAlongsideTransition({ (context) in }, completion: nil) } override func presentationTransitionDidEnd(completed: Bool) { print("didEnd") } override func dismissalTransitionWillBegin() { } override func dismissalTransitionDidEnd(completed: Bool) { } }
mit
xylxi/SLWebImage
SLImageCacheDemo/SLImageCacheDemo/ViewController.swift
1
3113
// // ViewController.swift // SLImageCache // // Created by DMW_W on 16/7/4. // Copyright © 2016年 XYLXI. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 200 let yepAvatarURLStrings = [ "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/84c9a0a9-c6eb-4495-9b50-0d551749956a", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/7cf09c38-355b-4daa-b733-5fede0181e5f", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-2.jpg", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/0e47196b-1656-4b79-8953-457afaca6f7b", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/e2b84ebe-533d-4845-a842-774de98c8504", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/e24117db-d360-4c0b-8159-c908bf216e38", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/0738b75f-b223-4e34-a61c-add693f99f74", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-8.jpg", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/134f80a5-d273-4e7c-b490-f0de862c4ac4", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/d0c29846-e064-4b4c-b4aa-bd0bd2d8d435", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/d124dcfe-07ec-4ac6-aaf3-5ba6afd131ad", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/70f6f156-7707-471d-8c98-fcb7d2a6edb1", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/24795538-fc57-428b-843e-211e6b89a00c", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/70a3d702-7769-4616-8410-0a7f5d39d883", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/db49a8c6-dd2f-464d-8d06-03e7268c7fb4", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-1.jpg", ] for str in yepAvatarURLStrings { self.datas.append(NSURL(string: str)!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var datas = [NSURL]() } extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.datas.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("SLTableViewCell", forIndexPath: indexPath) as! SLTableViewCell cell.model = self.datas[indexPath.row]; if indexPath.row == 0 { print(cell.imgView.sl_url) } return cell; } } class SLTableViewCell: UITableViewCell { @IBOutlet weak var imgView: UIImageView! var model: NSURL! { didSet { self.imgView.sl_setImageWithURL(model); } } }
mit
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/SpringAnimation.swift
1
2240
// // SpringAnimation.swift // Example // // Created by Wojciech Lukaszuk on 06/09/14. // Copyright (c) 2014 Wojtek Lukaszuk. All rights reserved. // import QuartzCore class SpringAnimation: CAKeyframeAnimation { var damping: CGFloat = 10.0 var mass: CGFloat = 1.0 var stiffness: CGFloat = 300.0 var velocity: CGFloat = 0 var fromValue: CGFloat = 0.0 var toValue: CGFloat = 0.0 override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! SpringAnimation duration = durationForEpsilon(0.01) copy.values = interpolatedValues() copy.duration = duration copy.mass = mass copy.stiffness = stiffness copy.damping = damping copy.velocity = velocity copy.fromValue = fromValue copy.toValue = toValue return copy } func interpolatedValues() -> [CGFloat] { var values: [CGFloat] = [] var value: CGFloat = 0 let valuesCount: Int = Int(duration * 60) let ω0: CGFloat = sqrt(stiffness / mass) // angular frequency let β: CGFloat = damping / (2 * mass) // amount of damping let v0 : CGFloat = velocity let x0: CGFloat = 1 // substituted initial value for i in 0..<valuesCount { let t: CGFloat = CGFloat(i)/60.0 if β < ω0 { // underdamped let ω1: CGFloat = sqrt(ω0 * ω0 - β * β) value = exp(-β * t) * (x0 * cos(ω1 * t) + CGFloat((β * x0 + v0) / ω1) * sin(ω1 * t)) } else if β == ω0 { // critically damped value = exp(-β * t) * (x0 + (β * x0 + v0) * t) } else { // overdamped let ω2: CGFloat = sqrt(β * β - ω0 * ω0) let sinhVal = sinh( ω2 * t) let coshVal = cosh(CGFloat(ω2 * t)) value = exp(-β * t) * (x0 * coshVal + ((β * x0 + v0) / ω2) * sinhVal) } values.append(toValue - value * (toValue - fromValue)) } return values } func durationForEpsilon(epsilon: CGFloat) -> CFTimeInterval { let beta: CGFloat = damping / (2 * mass) var duration: CGFloat = 0 while exp(-beta * duration) >= epsilon { duration += 0.1 } return CFTimeInterval(duration) } }
mit
Toxote/iOS
Toxote/Toxote/GameScene.swift
1
7230
// // GameScene.swift // SpriteKitSimpleGame // // Created by Laura Yang on 2017-01-27. // Copyright © 2017 Laura Yang. All rights reserved. // import SpriteKit func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } #if !(arch(x86_64) || arch(arm64)) func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x + y*y) } func normalized() -> CGPoint { return self / length() } } struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Monster : UInt32 = 0b1 // 1 static let Projectile: UInt32 = 0b10 // 2 } class GameScene: SKScene, SKPhysicsContactDelegate { // 1 let player = SKSpriteNode(imageNamed: "player") var monstersDestroyed = 0 override func didMove(to view: SKView) { // 2 backgroundColor = SKColor.white // 3 player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5) // 4 addChild(player) physicsWorld.gravity = CGVector.zero physicsWorld.contactDelegate = self run(SKAction.repeatForever( SKAction.sequence([ SKAction.run(addMonster), SKAction.wait(forDuration: 0.5) ]) )) let backgroundMusic = SKAudioNode(fileNamed: "background-music-aac.caf") backgroundMusic.autoplayLooped = true addChild(backgroundMusic) } func random() -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) } func random(min: CGFloat, max: CGFloat) -> CGFloat { return random() * (max - min) + min } func addMonster() { // Create sprite let monster = SKSpriteNode(imageNamed: "monster") monster.physicsBody = SKPhysicsBody(rectangleOf: monster.size) // 1 monster.physicsBody?.isDynamic = true // 2 monster.physicsBody?.categoryBitMask = PhysicsCategory.Monster // 3 monster.physicsBody?.contactTestBitMask = PhysicsCategory.Projectile // 4 monster.physicsBody?.collisionBitMask = PhysicsCategory.None // 5 // Determine where to spawn the monster along the Y axis let actualY = random(min: monster.size.height/2, max: size.height - monster.size.height/2) // Position the monster slightly off-screen along the right edge, // and along a random position along the Y axis as calculated above monster.position = CGPoint(x: size.width + monster.size.width/2, y: actualY) // Add the monster to the scene addChild(monster) // Determine speed of the monster let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0)) // Create the actions let actionMove = SKAction.move(to: CGPoint(x: -monster.size.width/2, y: actualY), duration: TimeInterval(actualDuration)) let actionMoveDone = SKAction.removeFromParent() let loseAction = SKAction.run() { let reveal = SKTransition.flipHorizontal(withDuration: 0.5) let gameOverScene = GameOverScene(size: self.size, won: false) self.view?.presentScene(gameOverScene, transition: reveal) } monster.run(SKAction.sequence([actionMove, loseAction, actionMoveDone])) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { run(SKAction.playSoundFileNamed("pew-pew-lei.caf", waitForCompletion: false)) // 1 - Choose one of the touches to work with guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) // 2 - Set up initial location of projectile let projectile = SKSpriteNode(imageNamed: "projectile") projectile.position = player.position projectile.physicsBody = SKPhysicsBody(circleOfRadius: projectile.size.width/2) projectile.physicsBody?.isDynamic = true projectile.physicsBody?.categoryBitMask = PhysicsCategory.Projectile projectile.physicsBody?.contactTestBitMask = PhysicsCategory.Monster projectile.physicsBody?.collisionBitMask = PhysicsCategory.None projectile.physicsBody?.usesPreciseCollisionDetection = true // 3 - Determine offset of location to projectile let offset = touchLocation - projectile.position // 4 - Bail out if you are shooting down or backwards if (offset.x < 0) { return } // 5 - OK to add now - you've double checked position addChild(projectile) // 6 - Get the direction of where to shoot let direction = offset.normalized() // 7 - Make it shoot far enough to be guaranteed off screen let shootAmount = direction * 1000 // 8 - Add the shoot amount to the current position let realDest = shootAmount + projectile.position // 9 - Create the actions let actionMove = SKAction.move(to: realDest, duration: 2.0) let actionMoveDone = SKAction.removeFromParent() projectile.run(SKAction.sequence([actionMove, actionMoveDone])) } func projectileDidCollideWithMonster(projectile: SKSpriteNode, monster: SKSpriteNode) { print("Hit") projectile.removeFromParent() monster.removeFromParent() monstersDestroyed += 1 if (monstersDestroyed > 30) { let reveal = SKTransition.flipHorizontal(withDuration: 0.5) let gameOverScene = GameOverScene(size: self.size, won: true) self.view?.presentScene(gameOverScene, transition: reveal) } } func didBegin(_ contact: SKPhysicsContact) { // 1 var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // 2 if ((firstBody.categoryBitMask & PhysicsCategory.Monster != 0) && (secondBody.categoryBitMask & PhysicsCategory.Projectile != 0)) { if let monster = firstBody.node as? SKSpriteNode, let projectile = secondBody.node as? SKSpriteNode { projectileDidCollideWithMonster(projectile: projectile, monster: monster) } } } }
gpl-3.0
adamahrens/braintweak
BrainTweak/BrainTweak/TableCell/MathCell.swift
1
460
// // MathCell.swift // BrainTweak // // Created by Adam Ahrens on 2/22/15. // Copyright (c) 2015 Appsbyahrens. All rights reserved. // import UIKit class MathCell: UITableViewCell { @IBOutlet weak var mathProblem: UILabel! override func prepareForReuse() { self.backgroundColor = UIColor.whiteColor() self.contentView.backgroundColor = UIColor.whiteColor() mathProblem.backgroundColor = UIColor.whiteColor() } }
mit
artman/Geometry
GeometryTests/GeometryTests.swift
1
4088
// // GeometryTests.swift // GeometryTests // // Created by Tuomas Artman on 7.9.2014. // Copyright (c) 2014 Tuomas Artman. All rights reserved. // import UIKit import XCTest import Geometry class GeometryTests: XCTestCase { func testRect() { var rect = CGRect(x: 10, y: 10, width: 20, height: 20) rect.top += 5 XCTAssertEqual(rect, CGRect(x: 10, y: 15, width: 20, height: 20), "Should modified rect correctly") rect.left += 5 XCTAssertEqual(rect, CGRect(x: 15, y: 15, width: 20, height: 20), "Should modified rect correctly") rect.bottom -= 10 XCTAssertEqual(rect, CGRect(x: 15, y: 5, width: 20, height: 20), "Should modified rect correctly") rect.right -= 10 XCTAssertEqual(rect, CGRect(x: 5, y: 5, width: 20, height: 20), "Should modified rect correctly") rect.size.width = 30 rect.size.height = 40 XCTAssertEqual(rect.center, CGPoint(x: 20, y: 25), "Should modified rect correctly") XCTAssertEqual(rect.centerX, 20, "Should modified rect correctly") XCTAssertEqual(rect.centerY, 25, "Should modified rect correctly") rect.centerX = 100 XCTAssertEqual(rect, CGRect(x: 85, y: 5, width: 30, height: 40), "Should modified rect correctly") rect.centerY = 100 XCTAssertEqual(rect, CGRect(x: 85, y: 80, width: 30, height: 40), "Should modified rect correctly") rect.center = CGPoint(x: 10, y:10) XCTAssertEqual(rect, CGRect(x: -5, y: -10, width: 30, height: 40), "Should modified rect correctly") } func testUIView() { let view = UIView(frame: "10, 10, 20, 20") view.top += 5 XCTAssertEqual(view.frame, CGRect(x: 10, y: 15, width: 20, height: 20), "Should modified rect correctly") view.left += 5 XCTAssertEqual(view.frame, CGRect(x: 15, y: 15, width: 20, height: 20), "Should modified rect correctly") view.bottom -= 10 XCTAssertEqual(view.frame, CGRect(x: 15, y: 5, width: 20, height: 20), "Should modified rect correctly") view.right -= 10 XCTAssertEqual(view.frame, CGRect(x: 5, y: 5, width: 20, height: 20), "Should modified rect correctly") view.width += 10 XCTAssertEqual(view.frame, CGRect(x: 5, y: 5, width: 30, height: 20), "Should modified rect correctly") view.height += 20 XCTAssertEqual(view.frame, CGRect(x: 5, y: 5, width: 30, height: 40), "Should modified rect correctly") XCTAssertEqual(view.center, CGPoint(x: 20, y: 25), "Should modified rect correctly") XCTAssertEqual(view.centerX, 20, "Should modified rect correctly") XCTAssertEqual(view.centerY, 25, "Should modified rect correctly") view.centerX = 100 XCTAssertEqual(view.frame, CGRect(x: 85, y: 5, width: 30, height: 40), "Should modified rect correctly") view.centerY = 100 XCTAssertEqual(view.frame, CGRect(x: 85, y: 80, width: 30, height: 40), "Should modified rect correctly") view.center = CGPoint(x: 10, y:10) XCTAssertEqual(view.frame, CGRect(x: -5, y: -10, width: 30, height: 40), "Should modified rect correctly") } func testRectStringConversion() { let rect: CGRect = "10, 20, 50, 60" XCTAssertEqual(rect, CGRect(x: 10, y: 20, width: 50, height: 60), "Should have create from string") let view = UIView(frame: "{{10, 20}, {50, 60}}") XCTAssertEqual(view.frame, CGRect(x: 10, y: 20, width: 50, height: 60), "Should have create from string") } func testPointStringConversion() { let point: CGPoint = "10, 20" XCTAssertEqual(point, CGPoint(x: 10, y: 20), "Should have create from string") let view = UIView(frame: "0, 0, 10, 10"); view.center = "10, 10" XCTAssertEqual(view.frame, CGRect(x: 5, y: 5, width: 10, height: 10), "Should have create from string") } }
mit
novi/mysql-swift
Tests/MySQLTests/QueryParameterTests.swift
1
12457
// // QueryParameterTests.swift // MySQL // // Created by Yusuke Ito on 4/21/16. // Copyright © 2016 Yusuke Ito. All rights reserved. // import XCTest import MySQL import SQLFormatter // the URL as QueryParameter should be extension URL: QueryParameter { public func queryParameter(option: QueryParameterOption) throws -> QueryParameterType { return self.absoluteString.queryParameter(option: option) } } extension QueryParameterTests { static var allTests : [(String, (QueryParameterTests) -> () throws -> Void)] { return [ ("testIDType", testIDType), ("testIDTypeInContainer", testIDTypeInContainer), ("testEnumType", testEnumType), ("testAutoincrementType", testAutoincrementType), ("testDateComponentsType", testDateComponentsType), ("testDataAndURLType", testDataAndURLType), ("testDecimalType", testDecimalType), ("testCodableIDType", testCodableIDType), ("testCodableIDType_AutoincrementNoID", testCodableIDType_AutoincrementNoID) ] } } final class QueryParameterTests: XCTestCase { private struct IDInt: IDType { let id: Int init(_ id: Int) { self.id = id } } private struct IDString: IDType { let id: String init(_ id: String) { self.id = id } } private struct ModelWithIDType_StringAutoincrement: Encodable, QueryParameter { let idStringAutoincrement: AutoincrementID<IDString> } private struct ModelWithIDType_IntAutoincrement: Encodable, QueryParameter { let idIntAutoincrement: AutoincrementID<IDInt> } private enum SomeEnumParameter: String, QueryRawRepresentableParameter { case first = "first 1" case second = "second' 2" } private enum SomeEnumCodable: String, Codable, QueryParameter { case first = "first 1" case second = "second' 2" } // https://developer.apple.com/documentation/swift/optionset private struct ShippingOptions: OptionSet, QueryRawRepresentableParameter { let rawValue: Int static let nextDay = ShippingOptions(rawValue: 1 << 0) static let secondDay = ShippingOptions(rawValue: 1 << 1) static let priority = ShippingOptions(rawValue: 1 << 2) static let standard = ShippingOptions(rawValue: 1 << 3) static let express: ShippingOptions = [.nextDay, .secondDay] static let all: ShippingOptions = [.express, .priority, .standard] } private struct ModelWithData: Encodable, QueryParameter { let data: Data } private struct ModelWithDate: Encodable, QueryParameter { let date: Date } private struct ModelWithDateComponents: Encodable, QueryParameter { let dateComponents: DateComponents } private struct ModelWithURL: Encodable, QueryParameter { let url: URL } private struct ModelWithDecimal: Encodable, QueryParameter { let value: Decimal } func testIDType() throws { let idInt: QueryParameter = IDInt(1234) XCTAssertEqual(try idInt.queryParameter(option: queryOption).escaped(), "1234") //let id: SomeID = try SomeID.fromSQLValue(string: "5678") //XCTAssertEqual(id.id, 5678) let idString: QueryParameter = IDString("123abc") XCTAssertEqual(try idString.queryParameter(option: queryOption).escaped(), "'123abc'") let idIntAutoincrement: QueryParameter = AutoincrementID(IDInt(1234)) XCTAssertEqual(try idIntAutoincrement.queryParameter(option: queryOption).escaped(), "1234") let idStringAutoincrement: QueryParameter = AutoincrementID(IDString("123abc")) XCTAssertEqual(try idStringAutoincrement.queryParameter(option: queryOption).escaped(), "'123abc'") } func testIDTypeInContainer() throws { do { let param: QueryParameter = ModelWithIDType_IntAutoincrement(idIntAutoincrement: .ID(IDInt(1234))) XCTAssertEqual(try param.queryParameter(option: queryOption).escaped(), "`idIntAutoincrement` = 1234") } do { let param: QueryParameter = ModelWithIDType_StringAutoincrement(idStringAutoincrement: .ID(IDString("123abc"))) XCTAssertEqual(try param.queryParameter(option: queryOption).escaped(), "`idStringAutoincrement` = '123abc'") } } func testEnumType() throws { do { let someVal: QueryParameter = SomeEnumParameter.second let escaped = "second' 2".escaped() XCTAssertEqual(try someVal.queryParameter(option: queryOption).escaped() , escaped) } do { let someVal: QueryParameter = SomeEnumCodable.second let escaped = "second' 2".escaped() XCTAssertEqual(try someVal.queryParameter(option: queryOption).escaped() , escaped) } do { let someOption: QueryParameter = ShippingOptions.all XCTAssertEqual(try someOption.queryParameter(option: queryOption).escaped() , "\(ShippingOptions.all.rawValue)") } } func testAutoincrementType() throws { let userID: AutoincrementID<UserID> = .ID(UserID(333)) XCTAssertEqual(userID, AutoincrementID.ID(UserID(333))) let someStringID: AutoincrementID<SomeStringID> = .ID(SomeStringID("id678@")) XCTAssertEqual(someStringID, AutoincrementID.ID(SomeStringID("id678@"))) let noID: AutoincrementID<UserID> = .noID XCTAssertEqual(noID, AutoincrementID.noID) } func testDateComponentsType() throws { do { let compsEmpty = DateComponents() let model = ModelWithDateComponents(dateComponents: compsEmpty) let _ = try model.queryParameter(option: queryOption).escaped() XCTFail("this should be throws an error") } catch { // OK } do { // MySQL YEAR type var comps = DateComponents() comps.year = 2155 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '2155'") } do { // MySQL TIME type var comps = DateComponents() comps.hour = -838 comps.minute = 59 comps.second = 59 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '-838:59:59'") } do { // MySQL TIME type // with nanosecond var comps = DateComponents() comps.hour = -838 comps.minute = 59 comps.second = 59 comps.nanosecond = 1234567 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '-838:59:59.001235'") } do { // MySQL DATETIME, TIMESTAMP type var comps = DateComponents() comps.year = 9999 comps.month = 12 comps.day = 31 comps.hour = 23 comps.minute = 59 comps.second = 59 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '9999-12-31 23:59:59'") } do { // MySQL DATETIME, TIMESTAMP type // with nanosecond var comps = DateComponents() comps.year = 9999 comps.month = 12 comps.day = 31 comps.hour = 23 comps.minute = 59 comps.second = 59 comps.nanosecond = 1234567 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '9999-12-31 23:59:59.001235'") } } func testDataAndURLType() throws { do { let dataModel = ModelWithData(data: Data([0x12, 0x34, 0x56, 0xff, 0x00])) let queryString = try dataModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`data` = x'123456ff00'") } do { let urlModel = ModelWithURL(url: URL(string: "https://apple.com/iphone")!) let queryString = try urlModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`url` = 'https://apple.com/iphone'") } do { let param: QueryParameter = URL(string: "https://apple.com/iphone")! let queryString = try param.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "'https://apple.com/iphone'") } } func testDecimalType() throws { let decimalModel = ModelWithDecimal(value: Decimal(1.2345e100)) let queryString = try decimalModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`value` = '12345000000000010240000000000000000000000000000000000000000000000000000000000000000000000000000000000'") } private enum UserType: String, Codable { case user = "user" case admin = "admin" } private struct CodableModel: Codable, QueryParameter { let id: UserID let name: String let userType: UserType } private struct CodableModelWithAutoincrement: Codable, QueryParameter { let id: AutoincrementID<UserID> let name: String let userType: UserType } func testCodableIDType() throws { let expectedResult = Set(arrayLiteral: "`id` = 123", "`name` = 'test4456'", "`userType` = 'user'") do { let parameter: QueryParameter = CodableModel(id: UserID(123), name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } do { let parameter: QueryParameter = CodableModelWithAutoincrement(id: AutoincrementID(UserID(123)), name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } } func testCodableIDType_AutoincrementNoID() throws { let expectedResult = Set(arrayLiteral: "`name` = 'test4456'", "`userType` = 'user'") let parameter: QueryParameter = CodableModelWithAutoincrement(id: .noID, name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } }
mit
practicalswift/swift
validation-test/compiler_crashers_fixed/25891-swift-type-print.swift
65
442
// 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 func a class a struct D:AnyObject class A:a
apache-2.0
practicalswift/swift
test/DebugInfo/while.swift
32
536
// RUN: %target-swift-frontend -g -emit-ir %s | %FileCheck %s func yieldValues() -> Int64? { return .none } // Verify that variables bound in the while statements are in distinct scopes. while let val = yieldValues() { // CHECK: !DILocalVariable(name: "val", scope: ![[SCOPE1:[0-9]+]] // CHECK: ![[SCOPE1]] = distinct !DILexicalBlock(scope: ![[MAIN:[0-9]+]] } while let val = yieldValues() { // CHECK: !DILocalVariable(name: "val", scope: ![[SCOPE2:[0-9]+]] // CHECK: ![[SCOPE2]] = distinct !DILexicalBlock(scope: ![[MAIN2:[0-9]+]] }
apache-2.0
practicalswift/swift
stdlib/public/core/StringUnicodeScalarView.swift
1
14991
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of Unicode scalar values. /// /// You can access a string's view of Unicode scalar values by using its /// `unicodeScalars` property. Unicode scalar values are the 21-bit codes /// that are the basic unit of Unicode. Each scalar value is represented by /// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit. /// /// let flowers = "Flowers 💐" /// for v in flowers.unicodeScalars { /// print(v.value) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 128144 /// /// Some characters that are visible in a string are made up of more than one /// Unicode scalar value. In that case, a string's `unicodeScalars` view /// contains more elements than the string itself. /// /// let flag = "🇵🇷" /// for c in flag { /// print(c) /// } /// // 🇵🇷 /// /// for v in flag.unicodeScalars { /// print(v.value) /// } /// // 127477 /// // 127479 /// /// You can convert a `String.UnicodeScalarView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) { /// let asciiPrefix = String(favemoji.unicodeScalars[..<i]) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " @_fixed_layout public struct UnicodeScalarView { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ _guts: _StringGuts) { self._guts = _guts _invariantCheck() } } } extension String.UnicodeScalarView { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Assert start/end are scalar aligned } #endif // INTERNAL_CHECKS_ENABLED } extension String.UnicodeScalarView: BidirectionalCollection { public typealias Index = String.Index /// The position of the first Unicode scalar value if the string is /// nonempty. /// /// If the string is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Index { @inline(__always) get { return _guts.startIndex } } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Index { @inline(__always) get { return _guts.endIndex } } /// Returns the next consecutive location after `i`. /// /// - Precondition: The next location exists. @inlinable @inline(__always) public func index(after i: Index) -> Index { _internalInvariant(i < endIndex) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.fastUTF8ScalarLength(startingAt: i._encodedOffset) return i.encoded(offsetBy: len) } return _foreignIndex(after: i) } /// Returns the previous consecutive location before `i`. /// /// - Precondition: The previous location exists. @inlinable @inline(__always) public func index(before i: Index) -> Index { precondition(i._encodedOffset > 0) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.withFastUTF8 { utf8 -> Int in return _utf8ScalarLength(utf8, endingAt: i._encodedOffset) } _internalInvariant(len <= 4, "invalid UTF8") return i.encoded(offsetBy: -len) } return _foreignIndex(before: i) } /// Accesses the Unicode scalar value at the given position. /// /// The following example searches a string's Unicode scalars view for a /// capital letter and then prints the character and Unicode scalar value /// at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.unicodeScalars[i])") /// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)") /// } /// // Prints "First capital letter: H" /// // Prints "Unicode scalar value: 72" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. @inlinable public subscript(position: Index) -> Unicode.Scalar { @inline(__always) get { String(_guts)._boundsCheck(position) let i = _guts.scalarAlign(position) return _guts.errorCorrectedScalar(startingAt: i._encodedOffset).0 } } } extension String.UnicodeScalarView { @_fixed_layout public struct Iterator: IteratorProtocol { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable @inline(__always) public mutating func next() -> Unicode.Scalar? { guard _fastPath(_position < _end) else { return nil } let (result, len) = _guts.errorCorrectedScalar(startingAt: _position) _position &+= len return result } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } } extension String.UnicodeScalarView: CustomStringConvertible { @inlinable public var description: String { @inline(__always) get { return String(_guts) } } } extension String.UnicodeScalarView: CustomDebugStringConvertible { public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } } extension String { /// Creates a string corresponding to the given collection of Unicode /// scalars. /// /// You can use this initializer to create a new string from a slice of /// another string's `unicodeScalars` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") { /// let adjective = String(picnicGuest.unicodeScalars[..<i]) /// print(adjective) /// } /// // Prints "Deserving" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.unicodeScalars` view. /// /// - Parameter unicodeScalars: A collection of Unicode scalar values. @inlinable @inline(__always) public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._guts) } /// The index type for a string's `unicodeScalars` view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index /// The string's value represented as a collection of Unicode scalar values. @inlinable public var unicodeScalars: UnicodeScalarView { @inline(__always) get { return UnicodeScalarView(_guts) } @inline(__always) set { _guts = newValue._guts } } } extension String.UnicodeScalarView : RangeReplaceableCollection { /// Creates an empty view instance. @inlinable @inline(__always) public init() { self.init(_StringGuts()) } /// Reserves enough space in the view's underlying storage to store the /// specified number of ASCII characters. /// /// Because a Unicode scalar value can require more than a single ASCII /// character's worth of storage, additional allocation may be necessary /// when adding to a Unicode scalar view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { self._guts.reserveCapacity(n) } /// Appends the given Unicode scalar to the view. /// /// - Parameter c: The character to append to the string. public mutating func append(_ c: Unicode.Scalar) { self._guts.append(String(c)._guts) } /// Appends the Unicode scalar values in the given sequence to the view. /// /// - Parameter newElements: A sequence of Unicode scalar values. /// /// - Complexity: O(*n*), where *n* is the length of the resulting view. public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Unicode.Scalar { // TODO(String performance): Skip extra String allocation let scalars = String(decoding: newElements.map { $0.value }, as: UTF32.self) self = (String(self._guts) + scalars).unicodeScalars } /// Replaces the elements within the specified bounds with the given Unicode /// scalar values. /// /// Calling this method invalidates any existing indices for use with this /// string. /// /// - Parameters: /// - bounds: The range of elements to replace. The bounds of the range /// must be valid indices of the view. /// - newElements: The new Unicode scalar values to add to the string. /// /// - Complexity: O(*m*), where *m* is the combined length of the view and /// `newElements`. If the call to `replaceSubrange(_:with:)` simply /// removes elements at the end of the string, the complexity is O(*n*), /// where *n* is equal to `bounds.count`. public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C : Collection, C.Element == Unicode.Scalar { // TODO(String performance): Skip extra String and Array allocation let utf8Replacement = newElements.flatMap { String($0).utf8 } let replacement = utf8Replacement.withUnsafeBufferPointer { return String._uncheckedFromUTF8($0) } var copy = String(_guts) copy.replaceSubrange(bounds, with: replacement) self = copy.unicodeScalars } } // Index conversions extension String.UnicodeScalarIndex { /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `unicodeScalars` view: /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)! /// /// print(String(cafe.unicodeScalars[..<scalarIndex])) /// // Prints "Café" /// /// If the index passed as `sourcePosition` doesn't have an exact /// corresponding position in `unicodeScalars`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair results in `nil`. /// /// - Parameters: /// - sourcePosition: A position in the `utf16` view of a string. /// `utf16Index` must be an element of /// `String(unicodeScalars).utf16.indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init?( _ sourcePosition: String.Index, within unicodeScalars: String.UnicodeScalarView ) { guard unicodeScalars._guts.isOnUnicodeScalarBoundary(sourcePosition) else { return nil } self = sourcePosition } /// Returns the position in the given string that corresponds exactly to this /// index. /// /// This example first finds the position of a space (UTF-8 code point `32`) /// in a string's `utf8` view and then uses this method find the same position /// in the string. /// /// let cafe = "Café 🍵" /// let i = cafe.unicodeScalars.firstIndex(of: "🍵") /// let j = i.samePosition(in: cafe)! /// print(cafe[j...]) /// // Prints "🍵" /// /// - Parameter characters: The string to use for the index conversion. /// This index must be a valid index of at least one view of `characters`. /// - Returns: The position in `characters` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `characters`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-8 continuation byte /// returns `nil`. public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } } // Reflection extension String.UnicodeScalarView : CustomReflectable { /// Returns a mirror that reflects the Unicode scalars view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.unicodeScalars[ /// someString.unicodeScalars.startIndex /// ..< someString.unicodeScalars.endIndex] /// /// was deduced to be of type `String.UnicodeScalarView`. Provide a /// more-specific Swift-3-only `subscript` overload that continues to produce /// `String.UnicodeScalarView`. extension String.UnicodeScalarView { public typealias SubSequence = Substring.UnicodeScalarView @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence { return String.UnicodeScalarView.SubSequence(self, _bounds: r) } } // Foreign string Support extension String.UnicodeScalarView { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: i) let len = _isLeadingSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: len) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) let priorIdx = i.priorEncoded let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: priorIdx) let len = _isTrailingSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: -len) } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinDomain/AssetInformation/Model/AssetInformation.swift
1
1391
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import MoneyKit public struct AssetInformation: Hashable { public let description: String? public let whitepaper: URL? public let website: URL? public var isEmpty: Bool { description.isNilOrEmpty && website.isNil } public init( description: String?, whitepaper: String?, website: String? ) { self.description = description self.whitepaper = whitepaper.flatMap(URL.init(string:)) self.website = website.flatMap(URL.init(string:)) } } // swiftlint:disable line_length extension AssetInformation { public static var preview: AssetInformation { AssetInformation( description: "Bitcoin uses peer-to-peer technology to operate with no central authority or banks; managing transactions and the issuing of bitcoins is carried out collectively by the network. Although other cryptocurrencies have come before, Bitcoin is the first decentralized cryptocurrency - Its reputation has spawned copies and evolution in the space.With the largest variety of markets and the biggest value - having reached a peak of 318 billion USD - Bitcoin is here to stay.", whitepaper: "https://www.cryptocompare.com/media/37745820/bitcoin.pdf", website: "https://bitcoin.org" ) } }
lgpl-3.0
KSU-Mobile-Dev-Club/Branching-Out-iOS
NearbyTreesTableViewCell.swift
1
317
// // NearbyTreesTableViewCell.swift // // // Created by Reagan Wood on 3/31/16. // // import Cocoa import UIKit class NearbyTreesTableViewCell: UITableViewCell { var treeDescriptionLabel: UILabel! var treeTitleLabel: UILabel! var treeDistanceLabel: UILabel! var treeImage: UIImageView! }
mit
DrabWeb/Azusa
Azusa.Previous/Azusa/Protocols/AZMusicPlayer.swift
1
6115
// // AZMusicPlayer.swift // Azusa // // Created by Ushio on 12/5/16. // import Foundation /// The protocol for some form of music player backend that Azusa can connect and use protocol AZMusicPlayer { // MARK: - Properties /// The key value pairs for the settings of this music player var settings : [String : Any] { get set }; /// The event subscriber for this music player var eventSubscriber : AZEventSubscriber { get set }; // MARK: - Functions // MARK: - Connection /// Starts up the connection to this music player backend and calls the given completion handler upon finishing(if given) /// /// - Parameter completionHandler: The closure to call when the connection function finishes, passed if it was successful(optional) func connect(_ completionHandler : ((Bool) -> ())?); // MARK: - Player /// Gets the current `AZPlayerStatus` of this music player /// /// - Parameter completionHandler: The completion handler to call with the retrieved `AZPlayerStatus` func getPlayerStatus(_ completionHandler : @escaping ((AZPlayerStatus) -> ())); /// Gets the elapsed time and duration of the current playing song, used for updating progress bars and similar /// /// - Parameter completionHandler: The completion handler for the request, passed the elapsed time of the current song in seconds func getElapsed(_ completionHandler : @escaping ((Int) -> ())); /// Seeks to `to` in the current playing song /// /// - Parameters: /// - to: The time in seconds to skip to /// - completionHandler: The completion handler to call when the operation finishes(optional) func seek(to : Int, completionHandler : (() -> ())?); /// Seeks to `to` in the song at `trackPosition` in the queue /// /// - Parameters: /// - to: The time in seconds to skip to /// - trackPosition: The position of the track in the queue to jump to /// - completionHandler: The completion handler to call when the operation finishes(optional) func seek(to : Int, trackPosition : Int, completionHandler : (() -> ())?); /// Toggles the paused state of this music player /// /// - Parameters: /// - completionHandler: The completion handler to call when the operation finishes(optional), passed the paused state that was set func togglePaused(completionHandler : ((Bool) -> ())?); /// Sets the paused state of this music player /// /// - Parameters: /// - paused: The value to set paused to /// - completionHandler: The completion handler to call when the operation finishes(optional) func setPaused(_ paused : Bool, completionHandler : (() -> ())?); /// Stops playback for this music player /// /// - Parameter completionHandler: The completion handler to call when the operation finishes(optional) func stop(completionHandler : (() -> ())?); /// Skips to the next song in the queue /// /// - Parameter completionHandler: The completion handler to call when the operation finishes(optional) func skipNext(completionHandler : (() -> ())?); /// Skips to the previous song in the queue /// /// - Parameter completionHandler: The completion handler to call when the operation finishes(optional) func skipPrevious(completionHandler : (() -> ())?); /// Sets the volume of this music player to the given value /// /// - Parameters: /// - to: The volume to set /// - completionHandler: The completion handler to call when the operation finishes(optional) func setVolume(to : Int, completionHandler : (() -> ())?); /// Adds the given volume to the current volume /// /// - Parameters: /// - to: The value to add to the volume, relative to the current volume(-100 to 100) /// - completionHandler: The completion handler to call when the operation finishes(optional) func setRelativeVolume(to : Int, completionHandler : (() -> ())?); // MARK: - Queue /// Gets the current queue /// /// - Parameter completionHandler: The completion handler to call when the operation finishes, passed an array of `AZSong`s for the queue and the position of the current song in the queue(defaults to -1 if no song is playing) func getQueue(completionHandler : @escaping (([AZSong], Int) -> ())); /// Plays the given song if it's in the queue /// /// - Parameters: /// - song: The song to play /// - completionHandler: The completion handler to call when the operation finishes(optional), passed the song that was played(nil if `song` was not in the queue) func playSongInQueue(_ song : AZSong, completionHandler : ((AZSong?) -> ())?); /// Removes the given `AZSong`s from the queue /// /// - Parameters: /// - songs: The `AZSong`s to remove /// - completionHandler: The completion handler to call when the operation finishes(optional) func removeFromQueue(_ songs : [AZSong], completionHandler : (() -> ())?); /// Moves the given `AZSong`s in the queue to after the current song(do not use this for adding songs to the queue after the current song, only move queued songs) /// /// - Parameters: /// - songs: The `AZSong`s to move to after the current song /// - completionHandler: The completion handler to call when the operation finishes(optional) func moveAfterCurrent(_ songs : [AZSong], completionHandler : (() -> ())?); /// Shuffles the current queue /// /// - Parameter completionHandler: The completion handler to call when the operation finishes(optional) func shuffleQueue(completionHandler : (() -> ())?); /// Clears the current queue /// /// - Parameter completionHandler: The completion handler to call when the operation finishes(optional) func clearQueue(completionHandler : (() -> ())?); // MARK: - Initialization and Deinitialization init(settings : [String : Any]); }
gpl-3.0
blockchain/My-Wallet-V3-iOS
Modules/Analytics/Sources/AnalyticsKit/Providers/Nabu/TokenProvider/TokenProvider.swift
1
248
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation /// A closure that provides local JWT token which will embeded in the request's Authorization header. public typealias TokenProvider = () -> String?
lgpl-3.0
huonw/swift
benchmark/single-source/MapReduce.swift
9
5056
//===--- MapReduce.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Foundation public let MapReduce = [ BenchmarkInfo(name: "MapReduce", runFunction: run_MapReduce, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceAnyCollection", runFunction: run_MapReduceAnyCollection, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceAnyCollectionShort", runFunction: run_MapReduceAnyCollectionShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceClass", runFunction: run_MapReduceClass, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceClassShort", runFunction: run_MapReduceClassShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazyCollection", runFunction: run_MapReduceLazyCollection, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazyCollectionShort", runFunction: run_MapReduceLazyCollectionShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazySequence", runFunction: run_MapReduceLazySequence, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceSequence", runFunction: run_MapReduceSequence, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceShort", runFunction: run_MapReduceShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceShortString", runFunction: run_MapReduceShortString, tags: [.validation, .algorithm, .String]), BenchmarkInfo(name: "MapReduceString", runFunction: run_MapReduceString, tags: [.validation, .algorithm, .String]), ] @inline(never) public func run_MapReduce(_ N: Int) { var numbers = [Int](0..<1000) var c = 0 for _ in 1...N*100 { numbers = numbers.map { $0 &+ 5 } c += numbers.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceAnyCollection(_ N: Int) { let numbers = AnyCollection([Int](0..<1000)) var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceAnyCollectionShort(_ N: Int) { let numbers = AnyCollection([Int](0..<10)) var c = 0 for _ in 1...N*10000 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceShort(_ N: Int) { var numbers = [Int](0..<10) var c = 0 for _ in 1...N*10000 { numbers = numbers.map { $0 &+ 5 } c += numbers.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceSequence(_ N: Int) { let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil } var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazySequence(_ N: Int) { let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil } var c = 0 for _ in 1...N*100 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazyCollection(_ N: Int) { let numbers = [Int](0..<1000) var c = 0 for _ in 1...N*100 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazyCollectionShort(_ N: Int) { let numbers = [Int](0..<10) var c = 0 for _ in 1...N*10000 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceString(_ N: Int) { let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789" var c: UInt64 = 0 for _ in 1...N*100 { c += s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceShortString(_ N: Int) { let s = "12345" var c: UInt64 = 0 for _ in 1...N*100 { c += s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceClass(_ N: Int) { #if _runtime(_ObjC) let numbers = (0..<1000).map { NSDecimalNumber(value: $0) } var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0.intValue &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) #endif } @inline(never) public func run_MapReduceClassShort(_ N: Int) { #if _runtime(_ObjC) let numbers = (0..<10).map { NSDecimalNumber(value: $0) } var c = 0 for _ in 1...N*10000 { let mapped = numbers.map { $0.intValue &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) #endif }
apache-2.0
moked/iuob
iUOB 2/Controllers/Schedule Builder/OptionsVC.swift
1
16606
// // OptionsVC.swift // iUOB 2 // // Created by Miqdad Altaitoon on 12/17/16. // Copyright © 2016 Miqdad Altaitoon. All rights reserved. // import UIKit import Alamofire import Kanna import MBProgressHUD import NYAlertViewController /// first load all courses data. then, options filters: time and sections class OptionsVC: UIViewController { // MARK: - Properties @IBOutlet weak var totalCombinationsLabel: UILabel! @IBOutlet weak var tooMuchLabel: UILabel! @IBOutlet weak var workingDaysSegmentedControl: UISegmentedControl! @IBOutlet weak var startAtSegmentedControl: UISegmentedControl! @IBOutlet weak var finishAtSegmentedControl: UISegmentedControl! @IBOutlet weak var lecturesLocationsSegmentedControl: UISegmentedControl! @IBOutlet weak var filterChangedImageView: UIImageView! @IBOutlet weak var sectionsFilterOutlet: UIButton! @IBOutlet weak var nextButtonOutlet: UIBarButtonItem! var addedCourses: [String] = [] // added courses by the user var semester: Int = 0 var courseSectionDict = [String: [Section]]() // source of all sctions var filteredCourseSectionDict = [String: [Section]]() // courseSectionDict after applaying filters var filterChanged = false // if user used filter at last or not // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() nextButtonOutlet.isEnabled = false filterChangedImageView.isHidden = true tooMuchLabel.text = "" disableAll() sectionsFilterOutlet.layer.cornerRadius = 15 getDepartments() googleAnalytics() } func googleAnalytics() { if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!) let builder: NSObject = GAIDictionaryBuilder.createScreenView().build() tracker.send(builder as! [NSObject : AnyObject]) } } func disableAll() { workingDaysSegmentedControl.isEnabled = false startAtSegmentedControl.isEnabled = false finishAtSegmentedControl.isEnabled = false lecturesLocationsSegmentedControl.isEnabled = false sectionsFilterOutlet.isEnabled = false totalCombinationsLabel.text = "0" } func enableAll() { workingDaysSegmentedControl.isEnabled = true startAtSegmentedControl.isEnabled = true finishAtSegmentedControl.isEnabled = true lecturesLocationsSegmentedControl.isEnabled = true sectionsFilterOutlet.isEnabled = true } /// first, get department url to check if this semester available or not func getDepartments() { let url = "\(Constants.baseURL)/cgi/enr/schedule2.abrv" MBProgressHUD.showAdded(to: self.view, animated: true) Alamofire.request(url, method: .get, parameters: ["prog": "1", "cyer": "2016", "csms": semester]) .validate() .responseString { response in MBProgressHUD.hide(for: self.view, animated: true) if response.result.error == nil { let departments = UOBParser.parseDepartments(response.result.value!) if departments.count == 0 { self.showAlert(title: "Sorry", msg: "Schedule for 2016\\\(self.semester) is not available. Make sure you select the right semester.") } else { self.getNextCourseData(0) // get first course } } else { self.showAlert(title: "Error", msg: (response.result.error?.localizedDescription)!) } } } /// function to get all courses recuresvly /// /// - Parameter index: course index func getNextCourseData(_ index: Int) { let thisCourse = addedCourses[index] let seperate = thisCourse.index(thisCourse.endIndex, offsetBy: -3) // last three characters represent the courseNo e.g 101 in ITCS101 let courseNo = thisCourse.substring(from: seperate) let department = thisCourse.substring(to: seperate) var departmentCode = "" if let dCode = Constants.depCodeMapping[department] { departmentCode = dCode } let url = "\(Constants.baseURL)/cgi/enr/schedule2.contentpage" Alamofire.request(url, parameters: ["abv": department, "inl": "\(departmentCode)", "crsno": "\(courseNo)", "prog": "1", "crd": "3", "cyer": "2016", "csms": semester]) .validate() .responseString { response in if response.result.error == nil { self.parseResult(html: response.result.value!, index: index, course: thisCourse) } else { self.showAlert(title: "Error", msg: (response.result.error?.localizedDescription)!) } } } func parseResult(html: String, index: Int, course: String) { var allSections = [Section]() for section in UOBParser.parseSections(html) { if section.timing.count > 0 { // if it has a time (some sections come without time e.g for College of education) var sec = section sec.note = course allSections.append(sec) } } if allSections.count > 0 { courseSectionDict[course] = allSections // update dictinary } else { showAlert(title: "Course not found", msg: "Course [\(course)] not found") } // load others recuresvly if index + 1 < self.addedCourses.count { self.getNextCourseData(index + 1) } else { self.checkForFinalExamClashes() self.createTimeTable() self.updatePossibleCombinations() } } /// check if there is final exam clash between any 2 courses and alert the user func checkForFinalExamClashes() { let lazyMapCollection = courseSectionDict.keys let keysArray = Array(lazyMapCollection.map { String($0)! }) for i in 0..<keysArray.count { for j in i+1..<keysArray.count { let courseA = courseSectionDict[keysArray[i]]!.last! let courseB = courseSectionDict[keysArray[j]]!.last! if let finalDateA = courseA.finalExam.date, let finalDateB = courseB.finalExam.date { if finalDateA == finalDateB { if courseA.finalExam.startTime == courseB.finalExam.startTime { // clash self.showAlert(title: "Final exam clash", msg: "There is a clash in the final exam between \(keysArray[i]) and \(keysArray[j])") } } } } } } /// stupid function name. we just store the original courses/sections for later use func createTimeTable() { filteredCourseSectionDict = courseSectionDict } /// function will be called whenever the user change one of the options /// /// - Parameter sender: option segment control @IBAction func segmetChangeEvent(_ sender: UISegmentedControl) { if filterChanged { filterChanged = false self.filterChangedImageView.isHidden = true showAlert(title: "Reset", msg: "Filter has beed reset. Please use [Sections Filter] at last") } filteredCourseSectionDict = [:] // reset filtered for (course, sections) in courseSectionDict { filteredCourseSectionDict[course] = [] for section in sections { var passSection = false for timing in section.timing { if workingDaysSegmentedControl.selectedSegmentIndex > 0 { let workingDays = workingDaysSegmentedControl.titleForSegment(at: workingDaysSegmentedControl.selectedSegmentIndex)! for day in timing.day.characters { if (workingDays.range(of: "\(day)") == nil) { passSection = true // the section contain a day not in the user's selected working days break } } if passSection {break} // go for next section } if startAtSegmentedControl.selectedSegmentIndex > 0 { let startTime = startAtSegmentedControl.selectedSegmentIndex + 8 // 9,10,11,12 let timeArr = timing.timeFrom.components(separatedBy: ":") if timeArr.count > 1 { let sectionStartTime = Float(Float(timeArr[0])! + (Float(timeArr[1])! / 60.0)) if Float(startTime) > sectionStartTime { passSection = true break } } } if finishAtSegmentedControl.selectedSegmentIndex > 0 { let finishTime = finishAtSegmentedControl.selectedSegmentIndex + 11 // 12,1,2,3 let timeArr = timing.timeTo.components(separatedBy: ":") if timeArr.count > 1 { let sectionFinishTime = Float(Float(timeArr[0])! + (Float(timeArr[1])! / 60.0)) if Float(finishTime) < sectionFinishTime { passSection = true break } } } if lecturesLocationsSegmentedControl.selectedSegmentIndex > 0 { let room = timing.room var location = 0 // 0 = Sakheer, 1 = Isa Town if room.characters.count > 1 { if room.range(of: "-") != nil { let roomArr = room.components(separatedBy: "-") if let number = Int(roomArr[0]) { if number > 0 && number < 38 { location = 1 } } else if roomArr[0] == "A27" { location = 1 } } } if lecturesLocationsSegmentedControl.selectedSegmentIndex == 1 && location != 0 { passSection = true break } else if lecturesLocationsSegmentedControl.selectedSegmentIndex == 2 && location != 1 { passSection = true break } } } if passSection { continue } else { filteredCourseSectionDict[course]?.append(section) } } } updatePossibleCombinations() } func updatePossibleCombinations() { var totalCombinations = 1 for (_, sections) in filteredCourseSectionDict { totalCombinations *= sections.count } totalCombinationsLabel.text = "\(totalCombinations)" enableAll() if totalCombinations > 0 && totalCombinations < 20000 { nextButtonOutlet.isEnabled = true } else { nextButtonOutlet.isEnabled = false } if totalCombinations > 20000 { tooMuchLabel.text = "should be less than 20000" } else { tooMuchLabel.text = "" } } @IBAction func combinationsInfoButton(_ sender: Any) { showAlert(title: "Info", msg: "Number of possible combinations is the number of MAXIMUM possible combinations for the courses you entered. It should be less than 20000 in order to continue to the next page which will show you the TRUE number of combinations. You can minimize the number of possible combinations by selecting different options below.") } @IBAction func filterInfoButton(_ sender: Any) { // Filter has beed reset. Please use [Sections Filter] at last showAlert(title: "Info", msg: "Use [Section Filter] for extra options. You can choose what section you want to be included individually. Please use [Section Filter] after selecting the Working Days/Times/Location.") } func showAlert(title: String, msg: String) { let alertViewController = NYAlertViewController() alertViewController.title = title alertViewController.message = msg alertViewController.buttonCornerRadius = 20.0 alertViewController.view.tintColor = self.view.tintColor //alertViewController.cancelButtonColor = UIColor.redColor() alertViewController.destructiveButtonColor = UIColor(netHex:0xFFA739) alertViewController.swipeDismissalGestureEnabled = true alertViewController.backgroundTapDismissalGestureEnabled = true let cancelAction = NYAlertAction( title: "Close", style: .cancel, handler: { (action: NYAlertAction?) -> Void in self.dismiss(animated: true, completion: nil) } ) alertViewController.addAction(cancelAction) // Present the alert view controller self.present(alertViewController, animated: true, completion: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SectionsFilterSegue" { let destinationNavigationController = segue.destination as! UINavigationController let nextScene = destinationNavigationController.topViewController as? SectionsFilterVC nextScene!.courseSectionDict = courseSectionDict nextScene!.filteredCourseSectionDict = filteredCourseSectionDict } else if segue.identifier == "SummarySegue" { let nextScene = segue.destination as? SummaryVC nextScene!.filteredCourseSectionDict = filteredCourseSectionDict } } @IBAction func unwindToOptionsVC(segue: UIStoryboardSegue) { if let sectionsFilterVC = segue.source as? SectionsFilterVC { self.filteredCourseSectionDict = sectionsFilterVC.filteredCourseSectionDict self.filterChanged = sectionsFilterVC.filterChanged if self.filterChanged { self.filterChangedImageView.isHidden = false } else { self.filterChangedImageView.isHidden = true } updatePossibleCombinations() } } }
mit
googlearchive/science-journal-ios
ScienceJournal/Extensions/String+Pluralize.swift
1
3498
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// Extensions on String for Science Journal used for formatting localized strings. extension String { /// Returns the claim experiments claim all confirmation message, singular or plural based on item /// count, with the item count and email address included in the string. /// /// - Parameters: /// - itemCount: The item count. /// - email: The email address of the user. /// - Returns: The confirmation message. static func claimExperimentsClaimAllConfirmationMessage(withItemCount itemCount: Int, email: String) -> String { if itemCount == 1 { return String(format: String.claimAllExperimentsConfirmationMessage, email) } else { return String(format: String.claimAllExperimentsConfirmationMessagePlural, String(itemCount), email) } } /// Returns the claim experiments delete all confirmation message, singular or plural based on /// item count, with the item count included in the string. /// /// - Parameter itemCount: The item count. /// - Returns: The confirmation message. static func claimExperimentsDeleteAllConfirmationMessage(withItemCount itemCount: Int) -> String { if itemCount == 1 { return String.claimExperimentsDeleteAllConfirmationMessage } else { return String(format: String.claimExperimentsDeleteAllConfirmationMessagePlural, itemCount) } } /// Returns the claim experiment confirmation message with the email address included in the /// string. /// /// - Parameter email: The email address. /// - Returns: The confirmation message. static func claimExperimentConfirmationMessage(withEmail email: String) -> String { return String(format: String.claimExperimentConfirmationMessage, email) } /// Returns the number of notes in an experiment in a localized string, singular or plural, /// or empty string if none. /// e.g. "1 note", "42 notes", "". /// /// - Parameter count: The note count. /// - Returns: The localized string. static func notesDescription(withCount count: Int) -> String { if count == 0 { return "" } else if count == 1 { return String.experimentOneNote } else { return String(format: String.experimentManyNotes, count) } } /// Returns the number of recordings in an experiment in a localized string, singular or plural, /// or empty string if none. /// e.g. "1 recording", "42 recordings", "". /// /// - Parameter count: The recording count. /// - Returns: The localized string. static func trialsDescription(withCount count: Int) -> String { if count == 0 { return "" } else if count == 1 { return String.experimentOneRecording } else { return String(format: String.experimentManyRecordings, count) } } }
apache-2.0
tarunon/mstdn
Persistents/Sources/PersistentStoreProtocol.swift
1
1543
// // Storable.swift // mstdn // // Created by tarunon on 2017/04/22. // Copyright © 2017年 tarunon. All rights reserved. // import Foundation import Base public class PersistentStore<T> { let _restore: () throws -> T let _store: (T) throws -> Void public init(restore: @escaping () throws -> T, store: @escaping (T) throws -> Void) { self._restore = restore self._store = store } public func restore() throws -> T { return try _restore() } public func store(_ value: T) throws { try _store(value) } } extension PersistentStore { public func converted<U>(translation: @escaping (T) throws -> U, retranslation: @escaping (U) throws -> T) -> PersistentStore<U> { return PersistentStore<U>( restore: { () -> U in try translation(self.restore()) }, store: { (value) in try self.store(retranslation(value)) } ) } } public protocol Storable { func bool(_ key: String) -> PersistentStore<Bool> func int(_ key: String) -> PersistentStore<Int> func float(_ key: String) -> PersistentStore<Float> func string(_ key: String) -> PersistentStore<String> func data(_ key: String) -> PersistentStore<Data> } public extension Storable { public func typed<P: PersistentValueProtocol>(type: P.Type=P.self, _ key: String) -> PersistentStore<P> { return data(key).converted(translation: P.decode, retranslation: { try $0.encode() }) } }
mit
luispadron/GradePoint
GradePoint/Protocols/UIPickerFieldDataSource.swift
1
435
// // UIPickerFieldDataSource.swift // GradePoint // // Created by Luis Padron on 12/25/17. // Copyright © 2017 Luis Padron. All rights reserved. // protocol UIPickerFieldDataSource: class { func numberOfComponents(in field: UIPickerField) -> Int func numberOfRows(in compononent: Int, for field: UIPickerField) -> Int func titleForRow(_ row: Int, in component: Int, for field: UIPickerField) -> String? }
apache-2.0
davidjhodge/main-repository
SwiftSearchBar/SwiftSearchBar/ViewController.swift
1
289
// // ViewController.swift // SwiftSearchBar // // Created by David Hodge on 1/20/15. // Copyright (c) 2015 Genesis Apps, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
apache-2.0
izhuster/TechnicalTest
Xcode8/TechnicalTest/Pods/AlamofireImage/Source/Request+AlamofireImage.swift
2
10030
// Request+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(OSX) import Cocoa #endif extension Request { static var acceptableImageContentTypes: Set<String> = [ "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-ms-bmp", "image/x-win-bitmap" ] /** Adds the content types specified to the list of acceptable images content types for validation. - parameter contentTypes: The additional content types. */ public class func addAcceptableImageContentTypes(contentTypes: Set<String>) { Request.acceptableImageContentTypes.unionInPlace(contentTypes) } // MARK: - iOS, tvOS and watchOS #if os(iOS) || os(tvOS) || os(watchOS) /** Creates a response serializer that returns an image initialized from the response data using the specified image options. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - returns: An image response serializer. */ public class func imageResponseSerializer( imageScale imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true) -> ResponseSerializer<UIImage, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { return .Failure(error!) } guard let validData = data where validData.length > 0 else { return .Failure(Request.imageDataError()) } guard Request.validateContentTypeForRequest(request, response: response) else { return .Failure(Request.contentTypeValidationError()) } do { let image = try Request.imageFromResponseData(validData, imageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .Success(image) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage( imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true, completionHandler: Response<Image, NSError> -> Void) -> Self { return response( responseSerializer: Request.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } private class func imageFromResponseData(data: NSData, imageScale: CGFloat) throws -> UIImage { if let image = UIImage.af_threadSafeImageWithData(data, scale: imageScale) { return image } throw imageDataError() } private class var imageScale: CGFloat { #if os(iOS) || os(tvOS) return UIScreen.mainScreen().scale #elseif os(watchOS) return WKInterfaceDevice.currentDevice().screenScale #endif } #elseif os(OSX) // MARK: - OSX /** Creates a response serializer that returns an image initialized from the response data. - returns: An image response serializer. */ public class func imageResponseSerializer() -> ResponseSerializer<NSImage, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { return .Failure(error!) } guard let validData = data where validData.length > 0 else { return .Failure(Request.imageDataError()) } guard Request.validateContentTypeForRequest(request, response: response) else { return .Failure(Request.contentTypeValidationError()) } guard let bitmapImage = NSBitmapImageRep(data: validData) else { return .Failure(Request.imageDataError()) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .Success(image) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage(completionHandler: Response<Image, NSError> -> Void) -> Self { return response( responseSerializer: Request.imageResponseSerializer(), completionHandler: completionHandler ) } #endif // MARK: - Private - Shared Helper Methods private class func validateContentTypeForRequest( request: NSURLRequest?, response: NSHTTPURLResponse?) -> Bool { if let URL = request?.URL where URL.fileURL { return true } if let mimeType = response?.MIMEType where Request.acceptableImageContentTypes.contains(mimeType) { return true } return false } private class func contentTypeValidationError() -> NSError { let failureReason = "Failed to validate response due to unacceptable content type" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotDecodeContentData, userInfo: userInfo) } private class func imageDataError() -> NSError { let failureReason = "Failed to create a valid Image from the response data" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotDecodeRawData, userInfo: userInfo) } }
mit
yangyu2010/DouYuZhiBo
DouYuZhiBo/DouYuZhiBo/Class/Home/Controller/FunnyViewController.swift
1
946
// // FunnyViewController.swift // DouYuZhiBo // // Created by Young on 2017/2/28. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit fileprivate let kFunnyContentViewMaggin : CGFloat = 8 class FunnyViewController: BaseRoomViewController { fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel() override func setupUI() { super.setupUI() let layout = baseCollec.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize.zero baseCollec.contentInset = UIEdgeInsets(top: kFunnyContentViewMaggin, left: 0, bottom: 0, right: 0) } override func loadData() { viewModel = funnyVM funnyVM.requestFunnyData { self.baseCollec.reloadData() //请求数据完成,调用父类的,取消动画 self.loadDataFinished() } } }
mit
sonnygauran/trailer
Shared/Repo.swift
1
4540
import CoreData final class Repo: DataItem { @NSManaged var dirty: NSNumber? @NSManaged var fork: NSNumber? @NSManaged var fullName: String? @NSManaged var hidden: NSNumber? @NSManaged var inaccessible: NSNumber? @NSManaged var lastDirtied: NSDate? @NSManaged var webUrl: String? @NSManaged var displayPolicyForPrs: NSNumber? @NSManaged var displayPolicyForIssues: NSNumber? @NSManaged var pullRequests: Set<PullRequest> @NSManaged var issues: Set<Issue> class func repoWithInfo(info: [NSObject : AnyObject], fromServer: ApiServer) -> Repo { let r = DataItem.itemWithInfo(info, type: "Repo", fromServer: fromServer) as! Repo if r.postSyncAction?.integerValue != PostSyncAction.DoNothing.rawValue { r.fullName = N(info, "full_name") as? String r.fork = (N(info, "fork") as? NSNumber)?.boolValue r.webUrl = N(info, "html_url") as? String r.dirty = true r.inaccessible = false r.lastDirtied = NSDate() } return r } func shouldSync() -> Bool { return (self.displayPolicyForPrs?.integerValue ?? 0) > 0 || (self.displayPolicyForIssues?.integerValue ?? 0) > 0 } override func resetSyncState() { super.resetSyncState() dirty = true lastDirtied = never() } class func visibleReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "displayPolicyForPrs > 0 or displayPolicyForIssues > 0") return try! moc.executeFetchRequest(f) as! [Repo] } class func countVisibleReposInMoc(moc: NSManagedObjectContext) -> Int { let f = NSFetchRequest(entityName: "Repo") f.predicate = NSPredicate(format: "displayPolicyForPrs > 0 or displayPolicyForIssues > 0") return moc.countForFetchRequest(f, error: nil) } class func interestedInIssues() -> Bool { for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { if r.displayPolicyForIssues?.integerValue > 0 { return true } } return false } class func interestedInPrs() -> Bool { for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { if r.displayPolicyForPrs?.integerValue > 0 { return true } } return false } class func syncableReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "dirty = YES and (displayPolicyForPrs > 0 or displayPolicyForIssues > 0) and inaccessible != YES") return try! moc.executeFetchRequest(f) as! [Repo] } class func reposNotRecentlyDirtied(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.predicate = NSPredicate(format: "dirty != YES and lastDirtied < %@ and postSyncAction != %d and (displayPolicyForPrs > 0 or displayPolicyForIssues > 0)", NSDate(timeInterval: -3600, sinceDate: NSDate()), PostSyncAction.Delete.rawValue) f.includesPropertyValues = false f.returnsObjectsAsFaults = false return try! moc.executeFetchRequest(f) as! [Repo] } class func unsyncableReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "(not (displayPolicyForPrs > 0 or displayPolicyForIssues > 0)) or inaccessible = YES") return try! moc.executeFetchRequest(f) as! [Repo] } class func markDirtyReposWithIds(ids: NSSet, inMoc: NSManagedObjectContext) { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "serverId IN %@", ids) for repo in try! inMoc.executeFetchRequest(f) as! [Repo] { repo.dirty = repo.shouldSync() } } class func reposForFilter(filter: String?) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false if let filterText = filter where !filterText.isEmpty { f.predicate = NSPredicate(format: "fullName contains [cd] %@", filterText) } f.sortDescriptors = [ NSSortDescriptor(key: "fork", ascending: true), NSSortDescriptor(key: "fullName", ascending: true) ] return try! mainObjectContext.executeFetchRequest(f) as! [Repo] } class func countParentRepos(filter: String?) -> Int { let f = NSFetchRequest(entityName: "Repo") if let fi = filter where !fi.isEmpty { f.predicate = NSPredicate(format: "fork == NO and fullName contains [cd] %@", fi) } else { f.predicate = NSPredicate(format: "fork == NO") } return mainObjectContext.countForFetchRequest(f, error:nil) } }
mit
eridbardhaj/Weather
Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift
1
3919
// // ToJSON.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-13. // Copyright (c) 2014 hearst. All rights reserved. // import class Foundation.NSNumber private func setValue(value: AnyObject, forKey key: String, inout #dictionary: [String : AnyObject]) { return setValue(value, forKeyPathComponents: key.componentsSeparatedByString("."), dictionary: &dictionary) } private func setValue(value: AnyObject, forKeyPathComponents components: [String], inout #dictionary: [String : AnyObject]) { if components.isEmpty { return } let head = components.first! if components.count == 1 { return dictionary[head] = value } else { var child = dictionary[head] as? [String : AnyObject] if child == nil { child = [:] } let tail = Array(components[1..<components.count]) setValue(value, forKeyPathComponents: tail, dictionary: &child!) return dictionary[head] = child } } internal final class ToJSON { class func basicType<N>(field: N, key: String, inout dictionary: [String : AnyObject]) { func _setValue(value: AnyObject) { setValue(value, forKey: key, dictionary: &dictionary) } switch field { // basic Types case let x as NSNumber: _setValue(x) case let x as Bool: _setValue(x) case let x as Int: _setValue(x) case let x as Double: _setValue(x) case let x as Float: _setValue(x) case let x as String: _setValue(x) // Arrays with basic types case let x as Array<NSNumber>: _setValue(x) case let x as Array<Bool>: _setValue(x) case let x as Array<Int>: _setValue(x) case let x as Array<Double>: _setValue(x) case let x as Array<Float>: _setValue(x) case let x as Array<String>: _setValue(x) case let x as Array<AnyObject>: _setValue(x) // Dictionaries with basic types case let x as Dictionary<String, NSNumber>: _setValue(x) case let x as Dictionary<String, Bool>: _setValue(x) case let x as Dictionary<String, Int>: _setValue(x) case let x as Dictionary<String, Double>: _setValue(x) case let x as Dictionary<String, Float>: _setValue(x) case let x as Dictionary<String, String>: _setValue(x) case let x as Dictionary<String, AnyObject>: _setValue(x) default: //println("Default") return } } class func optionalBasicType<N>(field: N?, key: String, inout dictionary: [String : AnyObject]) { if let field = field { basicType(field, key: key, dictionary: &dictionary) } } class func object<N: Mappable>(field: N, key: String, inout dictionary: [String : AnyObject]) { setValue(Mapper().toJSON(field), forKey: key, dictionary: &dictionary) } class func optionalObject<N: Mappable>(field: N?, key: String, inout dictionary: [String : AnyObject]) { if let field = field { object(field, key: key, dictionary: &dictionary) } } class func objectArray<N: Mappable>(field: Array<N>, key: String, inout dictionary: [String : AnyObject]) { let JSONObjects = Mapper().toJSONArray(field) if !JSONObjects.isEmpty { setValue(JSONObjects, forKey: key, dictionary: &dictionary) } } class func optionalObjectArray<N: Mappable>(field: Array<N>?, key: String, inout dictionary: [String : AnyObject]) { if let field = field { objectArray(field, key: key, dictionary: &dictionary) } } class func objectDictionary<N: Mappable>(field: Dictionary<String, N>, key: String, inout dictionary: [String : AnyObject]) { let JSONObjects = Mapper().toJSONDictionary(field) if !JSONObjects.isEmpty { setValue(JSONObjects, forKey: key, dictionary: &dictionary) } } class func optionalObjectDictionary<N: Mappable>(field: Dictionary<String, N>?, key: String, inout dictionary: [String : AnyObject]) { if let field = field { objectDictionary(field, key: key, dictionary: &dictionary) } } }
mit
optimistapp/optimistapp
Optimist/SunBar.swift
1
1363
// // SunBar.swift // Optimist // // Created by Jacob Johannesen on 1/31/15. // Copyright (c) 2015 Optimist. All rights reserved. // import Foundation import UIKit import CoreGraphics public class SunBar: UIView { let STATUS_BAR_PADDING: CGFloat = 8.0 public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(netHex:0xffb242) let outerRingImage = UIImage(named: "outerRing") let outerRingImageView = UIImageView(image: outerRingImage) outerRingImageView.frame = CGRect(x: self.frame.width / 2 - outerRingImageView.frame.width / 2, y: self.frame.height / 2 - outerRingImageView.frame.height / 2 + STATUS_BAR_PADDING, width: outerRingImageView.frame.width, height: outerRingImageView.frame.height) self.addSubview(outerRingImageView) let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = 15 rotateAnimation.repeatCount = Float.infinity rotateAnimation.delegate = self outerRingImageView.layer.addAnimation(rotateAnimation, forKey: nil) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
mgireesh05/leetcode
LeetCodeSwiftPlayground.playground/Sources/number-of-segments-in-a-string.swift
1
394
/** * Solution to the problem: https://leetcode.com/problems/number-of-segments-in-a-string/ */ //Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground. public class Solution434 { public init(){ } public func countSegments(_ s: String) -> Int { return s.characters.split(separator: " ").count } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/05324-swift-sourcemanager-getmessage.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [k<h : a { func g: C { struct B<T { { enum S<b).e = ") class case c,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/08816-swift-sourcemanager-getmessage.swift
11
205
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d = [ { init { { } class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/04706-swift-sourcemanager-getmessage.swift
11
230
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ((() as a<T { struct A { class a<T { let a { { class case c,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/12032-swift-sourcemanager-getmessage.swift
11
244
// 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 { enum e { func b { ( [ { var P { { } { } { { } { { { class case ,
mit
tkester/swift-algorithm-club
Fixed Size Array/FixedSizeArray.playground/Contents.swift
1
1236
//: Playground - noun: a place where people can play // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif /* An unordered array with a maximum size. Performance is always O(1). */ struct FixedSizeArray<T> { private var maxSize: Int private var defaultValue: T private var array: [T] private (set) var count = 0 init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](repeating: defaultValue, count: maxSize) } subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } mutating func append(_ newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } mutating func removeAt(index: Int) -> T { assert(index >= 0) assert(index < count) count -= 1 let result = array[index] array[index] = array[count] array[count] = defaultValue return result } mutating func removeAll() { for i in 0..<count { array[i] = defaultValue } count = 0 } } var array = FixedSizeArray(maxSize: 5, defaultValue: 0) array.append(4) array.append(2) array[1] array.removeAt(index: 0) array.removeAll()
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/05669-swift-sourcemanager-getmessage.swift
11
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing init<T where T { class B<T { func g<T> { class b> { class case c,
mit
VernonVan/SmartClass
SmartClass/Paper/Create Paper/Model/Question.swift
1
3830
// // Question.swift // SmartClass // // Created by Vernon on 16/8/4. // Copyright © 2016年 Vernon. All rights reserved. // import Foundation import RealmSwift fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } class Question: Object { /// 题目序号 dynamic var index = 0 /// 题目类型 (0--单选题 1--多选题 2--判断题) dynamic var type = 0 /// 题目描述 dynamic var topic: String? /// 选项A dynamic var choiceA: String? /// 选项B dynamic var choiceB: String? /// 选项C dynamic var choiceC: String? /// 选项D dynamic var choiceD: String? /// 答案 dynamic var answers: String? /// 分值 let score = RealmOptional<Int>() /// 所属的试卷 // let paper = LinkingObjects(fromType: Paper.self, property: "questions") /// Transient:题目是否完成的标记 var isCompleted: Bool { switch type { case 0: return isCompletedSingleChoice() case 1: return isCompletedMultipleChoice() case 2: return isCompletedTrueOrFalse() default: return false } } func isCompletedSingleChoice() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) && !(choiceC?.isEmpty ?? true) && !(choiceD?.isEmpty ?? true) let validAnswer = answers==nil ? false : answers!.characters.count==1 let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswer && validScore } func isCompletedMultipleChoice() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) && !(choiceC?.isEmpty ?? true) && !(choiceD?.isEmpty ?? true) let validAnswers = answers==nil ? false : (answers!.characters.count>1 && answers!.characters.count<=4) let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswers && validScore } func isCompletedTrueOrFalse() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) let validAnswer = answers==nil ? false : answers!.characters.count==1 let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswer && validScore } } enum QuestionType: Int, CustomStringConvertible { /// 单选题 case singleChoice = 0 /// 多选题 case multipleChoice = 1 /// 判断题 case trueOrFalse = 2 init?(typeNum: Int) { switch typeNum { case 0: self = .singleChoice case 1: self = .multipleChoice case 2: self = .trueOrFalse default: return nil } } var description: String { switch self { case .singleChoice: return NSLocalizedString("单选题", comment: "") case .multipleChoice: return NSLocalizedString("多选题", comment: "") case .trueOrFalse: return NSLocalizedString("判断题", comment: "") } } }
mit
daggmano/photo-management-studio
src/Client/OSX/Photo Management Studio/Photo Management Studio/PubSub.swift
1
1960
import Foundation // ===================================================== enum LogLevel: Int { case Debug = 1, Info, Error } let log_level = LogLevel.Debug protocol Loggable { func log() func log_error() func log_debug() } extension String: Loggable { func log() { if log_level.rawValue <= LogLevel.Info.rawValue { print("[info]\t\(self)") } } func log_error() { if log_level.rawValue <= LogLevel.Error.rawValue { print("[error]\t\(self)") } } func log_debug() { if log_level.rawValue <= LogLevel.Debug.rawValue { print("[debug]\t\(self)") } } } // ===================================================== typealias Callback = (AnyObject) -> Void struct Event { static var events = Dictionary<String, Array<Callback>>() static func register(event: String, callback: Callback) { if (self.events[event] == nil) { "Initializing list for event '\(event)'".log_debug() self.events[event] = Array<Callback>() } if var callbacks = self.events[event] { callbacks.append(callback) self.events[event] = callbacks "Registered callback for event '\(event)'".log_debug() } else { "Failed to register callback for event \(event)".log_error() } } static func emit(event: String, obj: AnyObject) { "Emitting event '\(event)'".log_debug() if let events = self.events[event] { "Found list for event '\(event)', of length \(events.count)".log_debug() for callback in events { callback(obj) } } else { "Could not find callbacks for event '\(event)'".log_error() } } } // ===================================================== //protocol Evented { // func emit(message: String) -> Bool //}
mit
shnhrrsn/swift-router
Tests/UrlRouterTests.swift
2
3945
// // UrlRouterTests.swift // SHNUrlRouter // // Copyright (c) 2015-2018 Shaun Harrison // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import SHNUrlRouter class UrlRouterTests: XCTestCase { func testReadMeExample() { var router = UrlRouter() var selectedIndex = -1 var id = -1 var section: String? router.add("id", pattern: "[0-9]+") router.add("section", pattern: "profile|activity") router.register("feed") { (parameters) in selectedIndex = 0 } router.register("user/{id}/{section?}") { (parameters) in guard let stringId = parameters["id"], let intId = Int(stringId) else { return } selectedIndex = 1 id = intId section = parameters["section"] ?? "default" } XCTAssertTrue(router.dispatch(for: "http://example.com/feed")) XCTAssertEqual(selectedIndex, 0) XCTAssertFalse(router.dispatch(for: "http://example.com/user")) XCTAssertTrue(router.dispatch(for: "http://example.com/user/5")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "default") XCTAssertTrue(router.dispatch(for: "http://example.com/user/5/profile")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "profile") } func testBasicDispatchingOfRoutes() { var router = UrlRouter() var dispatched = false router.register("foo/bar") { _ in dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/bar")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithParameter() { var router = UrlRouter() var dispatched = false router.register("foo/{bar}") { parameters in XCTAssertEqual(parameters["bar"], "swift") dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithOptionalParameter() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{bar}/{baz?}") { parameters in dispatched = "\(parameters["bar"] ?? "").\(parameters["baz"] ?? "1")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/4")) XCTAssertEqual(dispatched, "swift.4") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertEqual(dispatched, "swift.1") } func testBasicDispatchingOfRoutesWithOptionalParameters() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{name}/boom/{age?}/{location?}") { parameters in dispatched = "\(parameters["name"] ?? "").\(parameters["age"] ?? "56").\(parameters["location"] ?? "ca")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/steve/boom")) XCTAssertEqual(dispatched, "steve.56.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4")) XCTAssertEqual(dispatched, "swift.4.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4/org")) XCTAssertEqual(dispatched, "swift.4.org") } }
mit
newlix/swift-less-sql-api
Carthage/Checkouts/swift-less-api/LessAPI.swift
1
1837
import Foundation public class LessAPI { public let URL:NSURL public var JWT:JSONWebToken? public init(server:String) { let suffix = server.hasSuffix("/") ? "" : "/" self.URL = NSURL(string: server + suffix)! self.JWT = try! JSONWebToken.fromNSUserDefaults() } public func call(path:String, params: [String:AnyObject], progress: NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = try HTTP.post(URL, json: params, headers: headers, progress: progress) return try parseJSON(http) } public func upload(path:String, data: NSData, progress:NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = HTTP.upload(URL, data: data, headers: headers, progress: progress) return try parseJSON(http) } public func upload(path:String, file: NSURL, progress:NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = HTTP.upload(URL, file: file, headers: headers, progress: progress) return try parseJSON(http) } } private func parseJSON(http:HTTP) throws -> AnyObject? { if http.statusCode == 200 { if http.result.length > 0 { return try? NSJSONSerialization.JSONObjectWithData(http.result, options: NSJSONReadingOptions()) } else { return nil } } throw Error.HTTPRequest(http) }
mit
Norod/Filterpedia
Filterpedia/customFilters/MercurializeFilter.swift
1
8533
// // MercurializeFilter.swift // Filterpedia // // Created by Simon Gladman on 19/01/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // 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, either version 3 of the License, or // (at your option) any later version. // // 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 CoreImage import SceneKit class MercurializeFilter: CIFilter { // MARK: Filter parameters var inputImage: CIImage? var inputEdgeThickness: CGFloat = 5 var inputScale: CGFloat = 10 // MARK: Shading image attributes var inputLightColor = CIColor(red: 1, green: 1, blue: 0.75) { didSet { sphereImage = nil } } var inputLightPosition = CIVector(x: 0, y: 1) { didSet { sphereImage = nil } } var inputAmbientLightColor = CIColor(red: 0.5, green: 0.5, blue: 0.75) { didSet { sphereImage = nil } } var inputShininess: CGFloat = 0.05 { didSet { sphereImage = nil } } // MARK: SceneKit Objects var sphereImage: CIImage? let material = SCNMaterial() let sceneKitView = SCNView() let omniLightNode = LightNode(type: .Omni) let ambientLightNode = LightNode(type: .Ambient) // MARK: Attributes override func setDefaults() { inputEdgeThickness = 5 inputLightColor = CIColor(red: 1, green: 1, blue: 0.75) inputLightPosition = CIVector(x: 0, y: 1) inputAmbientLightColor = CIColor(red: 0.5, green: 0.5, blue: 0.75) inputShininess = 0.05 inputScale = 10 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Mercurialize Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputLightColor": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIColor", kCIAttributeDisplayName: "Light Color", kCIAttributeDefault: CIColor(red: 1, green: 1, blue: 0.75), kCIAttributeType: kCIAttributeTypeColor], "inputLightPosition": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Light Position", kCIAttributeDefault: CIVector(x: 0, y: 1), kCIAttributeDescription: "Vector defining normalised light position. (0, 0) is bottom left, (1, 1) is top right.", kCIAttributeType: kCIAttributeTypeColor], "inputAmbientLightColor": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIColor", kCIAttributeDisplayName: "Ambient Light Color", kCIAttributeDefault: CIColor(red: 0.5, green: 0.5, blue: 0.75), kCIAttributeType: kCIAttributeTypeColor], "inputShininess": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Shininess", kCIAttributeDefault: 0.05, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 0.5, kCIAttributeType: kCIAttributeTypeScalar], "inputEdgeThickness": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Edge Thickness", kCIAttributeDefault: 5, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputScale": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Scale", kCIAttributeDefault: 10, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar] ] } // MARK: Initialisation override init() { super.init() setUpSceneKit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Output Image override var outputImage: CIImage! { guard let inputImage = inputImage else { return nil } if sphereImage == nil { material.shininess = inputShininess omniLightNode.color = inputLightColor omniLightNode.position.x = Float(-50 + (inputLightPosition.x * 100)) omniLightNode.position.y = Float(-50 + (inputLightPosition.y * 100)) ambientLightNode.color = inputAmbientLightColor sceneKitView.prepare(sceneKitView.scene!, shouldAbortBlock: {false}) sphereImage = CIImage(image: sceneKitView.snapshot()) } let edgeWork = CIFilter(name: "CIEdgeWork", withInputParameters: [kCIInputImageKey: inputImage, kCIInputRadiusKey: inputEdgeThickness])! let heightField = CIFilter(name: "CIHeightFieldFromMask", withInputParameters: [ kCIInputRadiusKey: inputScale, kCIInputImageKey: edgeWork.outputImage!])! let shadedMaterial = CIFilter(name: "CIShadedMaterial", withInputParameters: [ kCIInputScaleKey: inputScale, kCIInputImageKey: heightField.outputImage!, kCIInputShadingImageKey: sphereImage!])! return shadedMaterial.outputImage } // MARK: SceneKit set up func setUpSceneKit() { sceneKitView.frame = CGRect(x: 0, y: 0, width: 320, height: 320) sceneKitView.backgroundColor = UIColor.black let scene = SCNScene() sceneKitView.scene = scene let camera = SCNCamera() camera.usesOrthographicProjection = true camera.orthographicScale = 1 let cameraNode = SCNNode() cameraNode.camera = camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 2) scene.rootNode.addChildNode(cameraNode) // sphere... let sphere = SCNSphere(radius: 1) let sphereNode = SCNNode(geometry: sphere) sphereNode.position = SCNVector3(x: 0, y: 0, z: 0) scene.rootNode.addChildNode(sphereNode) // Lights scene.rootNode.addChildNode(ambientLightNode) scene.rootNode.addChildNode(omniLightNode) // Material material.lightingModel = SCNMaterial.LightingModel.phong material.specular.contents = UIColor.white material.diffuse.contents = UIColor.darkGray material.shininess = 0.15 sphere.materials = [material] } } /// LightNode class - SceneKit node with light class LightNode: SCNNode { required init(type: LightType) { super.init() light = SCNLight() light!.type = SCNLight.LightType(rawValue: type.rawValue) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var color: CIColor = CIColor(red: 0, green: 0, blue: 0) { didSet { light?.color = UIColor(ciColor: color) } } } enum LightType: String { case Ambient = "ambient" case Omni = "omni" case Directional = "directional" case Spot = "spot" }
gpl-3.0
rsyncOSX/RsyncOSX
RsyncOSX/TrimThree.swift
1
1199
// // TrimThree.swift // RsyncUI // // Created by Thomas Evensen on 05/05/2021. // import Combine import Foundation final class TrimThree: Errors { var subscriptions = Set<AnyCancellable>() var trimmeddata = [String]() var maxnumber: Int = 0 var errordiscovered: Bool = false init(_ data: [String]) { data.publisher .sink(receiveCompletion: { completion in switch completion { case .finished: return case let .failure(error): let error = error as NSError self.error(errordescription: error.description, errortype: .readerror) } }, receiveValue: { [unowned self] line in let substr = line.dropFirst(10).trimmingCharacters(in: .whitespacesAndNewlines) let str = substr.components(separatedBy: " ").dropFirst(3).joined(separator: " ") if str.isEmpty == false { if str.contains(".DS_Store") == false { trimmeddata.append(str) } } }) .store(in: &subscriptions) } }
mit
apple/swift
test/SourceKit/CodeComplete/Inputs/checkdeps/SwiftFW_src/Funcs.swift
22
47
public func swiftFWFunc() -> Int { return 1 }
apache-2.0
bustoutsolutions/siesta
Source/Siesta/Support/Regex+Siesta.swift
1
1097
// // Regex+Siesta.swift // Siesta // // Created by Paul on 2015/7/8. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation extension String { func contains(regex: String) -> Bool { range(of: regex, options: .regularExpression) != nil } func replacing(regex: String, with replacement: String) -> String { replacingOccurrences( of: regex, with: replacement, options: .regularExpression, range: nil) } func replacing(regex: NSRegularExpression, with template: String) -> String { regex.stringByReplacingMatches(in: self, options: [], range: fullRange, withTemplate: template) } fileprivate var fullRange: NSRange { NSRange(location: 0, length: (self as NSString).length) } } extension NSRegularExpression { func matches(_ string: String) -> Bool { let match = firstMatch(in: string, options: [], range: string.fullRange) return match != nil && match?.range.location != NSNotFound } }
mit
jmfieldman/Brisk
Brisk/BriskSync2Async.swift
1
22896
// // BriskSync2Async.swift // Brisk // // Copyright (c) 2016-Present Jason Fieldman - https://github.com/jmfieldman/Brisk // // 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 // MARK: - Routing Object public class __BriskRoutingObj<I, O> { // ---------- Properties ---------- // The dispatch group used in various synchronizing routines fileprivate let dispatchGroup = DispatchGroup() // This is the actual function that we are routing fileprivate let wrappedFunction: (I) -> O // If we are routing the response, this catches the value fileprivate var response: O? = nil // This is the queue that the function will be executed on fileprivate var opQueue: DispatchQueue? = nil // This is the queue that the handler will execute on (if needed) fileprivate var handlerQueue: DispatchQueue? = nil // The lock used to synchronize various accesses fileprivate var lock: NSLock = NSLock() // Is this routing object available to perform its operation? // The routing objects may only perform their operations once, they should // NOT be retained and called a second time. fileprivate var operated: Bool = false // ---------- Init ------------ // Instantiate ourselves with a function public init(function: @escaping (I) -> O, defaultOpQueue: DispatchQueue? = nil) { wrappedFunction = function opQueue = defaultOpQueue } // ---------- Queue Adjustments ------------- /// Returns the current routing object set to execute its /// function on the main queue public var main: __BriskRoutingObj<I, O> { self.opQueue = mainQueue return self } /// Returns the current routing object set to execute its /// function on the generic concurrent background queue public var background: __BriskRoutingObj<I, O> { self.opQueue = backgroundQueue return self } /// Returns the current routing object set to execute its /// function on the specified queue public func on(_ queue: DispatchQueue) -> __BriskRoutingObj<I, O> { self.opQueue = queue return self } // ----------- Execution ------------- /// The sync property returns a function with the same input/output /// parameters of the original function. It is executed asynchronously /// on the specified queue. The calling thread is blocked until the /// called function completes. Not compatible with functions that throw /// errors. public var sync: (I) -> O { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } // If we're synchronous on the main thread already, just run the function immediately. if opQ === mainQueue && Thread.current.isMainThread { return { i in return self.wrappedFunction(i) } } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } _ = self.dispatchGroup.wait(timeout: DispatchTime.distantFuture) return self.response! // Will be set in the async call above } } /// Processes the async handler applied to this routing object. fileprivate func processAsyncHandler(_ handler: @escaping (O) -> Void) { guard let hQ = self.handlerQueue else { brisk_raise("The handler queue was not specified before routing the async response") } backgroundQueue.async { _ = self.dispatchGroup.wait(timeout: DispatchTime.distantFuture) hQ.async { handler(self.response!) // Will be set in the async call before wait completes } } } } public final class __BriskRoutingObjVoid<I>: __BriskRoutingObj<I, Void> { // Instantiate ourselves with a function override public init(function: @escaping (I) -> Void, defaultOpQueue: DispatchQueue? = nil) { super.init(function: function, defaultOpQueue: defaultOpQueue) } /// The async property returns a function that takes the parameters /// from the original function, executes the function with those /// parameters in the desired queue, then returns Void back to the /// originating thread. (for functions that originally return Void) /// /// When calling the wrapped function, the internal dispatchQueue /// is not exited until the wrapped function completes. This /// internal dispatchQueue can be waited on to funnel the response /// of the wrapped function to yet another async dispatch. public var async: (I) -> Void { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } } } } public final class __BriskRoutingObjNonVoid<I, O>: __BriskRoutingObj<I, O> { // Instantiate ourselves with a function override public init(function: @escaping (I) -> O, defaultOpQueue: DispatchQueue? = nil) { super.init(function: function, defaultOpQueue: defaultOpQueue) } /// The async property returns a function that takes the parameters /// from the original function, executes the function with those /// parameters in the desired queue, then returns the original /// routing object back to the originating thread. /// /// When calling the wrapped function, the internal dispatchQueue /// is not exited until the wrapped function completes. This /// internal dispatchQueue can be waited on to funnel the response /// of the wrapped function to yet another async dispatch. public var async: (I) -> __BriskRoutingObjNonVoid<I, O> { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } return self } } } // MARK: - Operators postfix operator ->> postfix operator ~>> postfix operator +>> //postfix operator ?->> //postfix operator ?~>> //postfix operator ?+>> /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` @inline(__always) public postfix func ->><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function) } /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` @inline(__always) public postfix func ->><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function) } /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` //@inline(__always) public postfix func ?->><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!) //} /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` //@inline(__always) public postfix func ?->><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!) //} /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` public postfix func ~>><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function, defaultOpQueue: backgroundQueue) } /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` public postfix func ~>><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function, defaultOpQueue: backgroundQueue) } /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` //@inline(__always) public postfix func ?~>><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!, defaultOpQueue: backgroundQueue) //} /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` //@inline(__always) public postfix func ?~>><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!, defaultOpQueue: backgroundQueue) //} /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` public postfix func +>><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function, defaultOpQueue: mainQueue) } /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` public postfix func +>><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function, defaultOpQueue: mainQueue) } /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` //@inline(__always) public postfix func ?+>><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!, defaultOpQueue: mainQueue) //} /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` //@inline(__always) public postfix func ?+>><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!, defaultOpQueue: mainQueue) //} /* -- old precendence = 140 -- */ precedencegroup AsyncRedirectPrecendence { higherThan: RangeFormationPrecedence lowerThan: MultiplicationPrecedence associativity: left } infix operator +>> : AsyncRedirectPrecendence infix operator ~>> : AsyncRedirectPrecendence infix operator ?+>> : AsyncRedirectPrecendence infix operator ?~>> : AsyncRedirectPrecendence /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ~>><I>(lhs: @escaping (I) -> Void, rhs: I) -> Void { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ~>><I, O>(lhs: @escaping (I) -> O, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ~>><I>(lhs: __BriskRoutingObjVoid<I>, rhs: I) -> Void { return lhs.async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return lhs.async(rhs) } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ?~>><I>(lhs: ((I) -> Void)?, rhs: I) -> Void { if let lhs = lhs { __BriskRoutingObjVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ?~>><I, O>(lhs: ((I) -> O)?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ?~>><I>(lhs: __BriskRoutingObjVoid<I>?, rhs: I) -> Void { lhs?.async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ?~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return lhs?.async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` public func +>><I>(lhs: @escaping (I) -> Void, rhs: I) -> Void { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` @discardableResult public func +>><I, O>(lhs: @escaping (I) -> O, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` public func ?+>><I>(lhs: ((I) -> Void)?, rhs: I) -> Void { if let lhs = lhs { __BriskRoutingObjVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` @discardableResult public func ?+>><I, O>(lhs: ((I) -> O)?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: mainQueue).async(rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I>(lhs: @escaping (I) -> Void, rhs: DispatchQueue) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: @escaping (I) -> O, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator allows you to specify the queues for the /// routing operations. This sets the initial operation queue if it hasn't already /// been defined by on(). If the initial operation queue has already been defined, /// this sets the response handler queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O> { lhs.handlerQueue = rhs return lhs } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ?~>><I>(lhs: ((I) -> Void)?, rhs: DispatchQueue) -> __BriskRoutingObjVoid<I>? { return (lhs == nil) ? nil : __BriskRoutingObjVoid(function: lhs!, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ?~>><I, O>(lhs: ((I) -> O)?, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator allows you to specify the queues for the /// routing operations. This sets the initial operation queue if it hasn't already /// been defined by on(). If the initial operation queue has already been defined, /// this sets the response handler queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O>? { lhs?.handlerQueue = rhs return lhs } /// The ```~>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the predefined queue, or the global /// concurrent background queue by default if none was specified. /// /// -e.g.: ```handler~>>(param: nil) ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: @escaping (O) -> Void) { if lhs.handlerQueue == nil { lhs.handlerQueue = backgroundQueue } lhs.processAsyncHandler(rhs) } /// The ```+>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the main queue. /// /// -e.g.: ```handler~>>(param: nil) +>> { result in ... }``` public func +>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: @escaping (O) -> Void) { lhs.handlerQueue = mainQueue lhs.processAsyncHandler(rhs) } /// The ```~>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the predefined queue, or the global /// concurrent background queue by default if none was specified. /// /// -e.g.: ```handler~>>(param: nil) ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: @escaping (O) -> Void) { if let lhs = lhs { if lhs.handlerQueue == nil { lhs.handlerQueue = backgroundQueue } lhs.processAsyncHandler(rhs) } } /// The ```+>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the main queue. /// /// -e.g.: ```handler~>>(param: nil) +>> { result in ... }``` public func +>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: @escaping (O) -> Void) { lhs?.handlerQueue = mainQueue lhs?.processAsyncHandler(rhs) }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/26323-swift-genericparamlist-deriveallarchetypes.swift
1
458
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck { { if{{{extension{ extension{let c{ protocol A{class case,
apache-2.0
KyoheiG3/RxSwift
RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift
1
6412
// // TableViewWithEditingCommandsViewController.swift // RxExample // // Created by carlos on 26/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif /** Another way to do "MVVM". There are different ideas what does MVVM mean depending on your background. It's kind of similar like FRP. In the end, it doesn't really matter what jargon are you using. This would be the ideal case, but it's really hard to model complex views this way because it's not possible to observe partial model changes. */ struct TableViewEditingCommandsViewModel { let favoriteUsers: [User] let users: [User] func executeCommand(_ command: TableViewEditingCommand) -> TableViewEditingCommandsViewModel { switch command { case let .setUsers(users): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .setFavoriteUsers(favoriteUsers): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .deleteUser(indexPath): var all = [self.favoriteUsers, self.users] all[indexPath.section].remove(at: indexPath.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) case let .moveUser(from, to): var all = [self.favoriteUsers, self.users] let user = all[from.section][from.row] all[from.section].remove(at: from.row) all[to.section].insert(user, at: to.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) } } } enum TableViewEditingCommand { case setUsers(users: [User]) case setFavoriteUsers(favoriteUsers: [User]) case deleteUser(indexPath: IndexPath) case moveUser(from: IndexPath, to: IndexPath) } class TableViewWithEditingCommandsViewController: ViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let dataSource = TableViewWithEditingCommandsViewController.configureDataSource() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem let superMan = User( firstName: "Super", lastName: "Man", imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg" ) let watMan = User(firstName: "Wat", lastName: "Man", imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF" ) let loadFavoriteUsers = RandomUserAPI.sharedAPI .getExampleUserResultSet() .map(TableViewEditingCommand.setUsers) let initialLoadCommand = Observable.just(TableViewEditingCommand.setFavoriteUsers(favoriteUsers: [superMan, watMan])) .concat(loadFavoriteUsers) .observeOn(MainScheduler.instance) let deleteUserCommand = tableView.rx.itemDeleted.map(TableViewEditingCommand.deleteUser) let moveUserCommand = tableView .rx.itemMoved .map(TableViewEditingCommand.moveUser) let initialState = TableViewEditingCommandsViewModel(favoriteUsers: [], users: []) let viewModel = Observable.of(initialLoadCommand, deleteUserCommand, moveUserCommand) .merge() .scan(initialState) { $0.executeCommand($1) } .shareReplay(1) viewModel .map { [ SectionModel(model: "Favorite Users", items: $0.favoriteUsers), SectionModel(model: "Normal Users", items: $0.users) ] } .bindTo(tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView.rx.itemSelected .withLatestFrom(viewModel) { i, viewModel in let all = [viewModel.favoriteUsers, viewModel.users] return all[i.section][i.row] } .subscribe(onNext: { [weak self] user in self?.showDetailsForUser(user) }) .addDisposableTo(disposeBag) // customization using delegate // RxTableViewDelegateBridge will forward correct messages tableView.rx.setDelegate(self) .addDisposableTo(disposeBag) } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.isEditing = editing } // MARK: Table view delegate ;) func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let title = dataSource[section] let label = UILabel(frame: CGRect.zero) // hacky I know :) label.text = " \(title)" label.textColor = UIColor.white label.backgroundColor = UIColor.darkGray label.alpha = 0.9 return label } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } // MARK: Navigation private func showDetailsForUser(_ user: User) { let storyboard = UIStoryboard(name: "TableViewWithEditingCommands", bundle: Bundle(identifier: "RxExample-iOS")) let viewController = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController viewController.user = user self.navigationController?.pushViewController(viewController, animated: true) } // MARK: Work over Variable static func configureDataSource() -> RxTableViewSectionedReloadDataSource<SectionModel<String, User>> { let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>() dataSource.configureCell = { (_, tv, ip, user: User) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = user.firstName + " " + user.lastName return cell } dataSource.titleForHeaderInSection = { dataSource, sectionIndex in return dataSource[sectionIndex].model } dataSource.canEditRowAtIndexPath = { (ds, ip) in return true } dataSource.canMoveRowAtIndexPath = { _ in return true } return dataSource } }
mit
rrunfa/StreamRun
Libraries/Alamofire/ParameterEncoding.swift
3
9075
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** HTTP method definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS = "OPTIONS" case GET = "GET" case HEAD = "HEAD" case POST = "POST" case PUT = "PUT" case PATCH = "PATCH" case DELETE = "DELETE" case TRACE = "TRACE" case CONNECT = "CONNECT" } // MARK: - ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. */ public enum ParameterEncoding { /** A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). */ case URL /** Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. */ case JSON /** Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. */ case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) /** Uses the associated closure value to construct a new request given an existing request and parameters. */ case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. :param: URLRequest The request to have parameters applied :param: parameters The parameters to apply :returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest: NSMutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest if parameters == nil { return (mutableURLRequest, nil) } var error: NSError? = nil switch self { case .URL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in sorted(Array(parameters.keys), <) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return join("&", components.map{ "\($0)=\($1)" } as [String]) } func encodesParametersInURL(method: Method) -> Bool { switch method { case .GET, .HEAD, .DELETE: return true default: return false } } let method = Method(rawValue: mutableURLRequest.HTTPMethod) if let method = method where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!) mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } case .JSON: let options = NSJSONWritingOptions.allZeros if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) { mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } case .PropertyList(let (format, options)): if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) { mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } case .Custom(let closure): (mutableURLRequest, error) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, error) } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.extend([(escape(key), escape("\(value)"))]) } return components } /** Returns a percent escaped string following RFC 3986 for query string formatting. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" Core Foundation interprets RFC 3986 in terms of legal and illegal characters. - Legal Numbers: "0123456789" - Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", "\"" - Illegal Characters: All characters not listed as Legal While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This explains why it does not consider "[", "]" and "#" to be "legal" characters even though they are specified as "reserved" characters in RFC 3986. The following rdar has been filed to hopefully get the documentation updated. - https://openradar.appspot.com/radar?id=5058257274011648 In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent escaped in the query string. :param: string The string to be percent escaped. :returns: The percent escaped string. */ func escape(string: String) -> String { let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimiters = "!$&'()*+,;=" let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/15757-swift-sourcemanager-getmessage.swift
11
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { struct S { let a { init( ) { class case ,
mit
nghiaphunguyen/NKit
NKit/Source/Utilities/NKTimeChecker.swift
1
1398
// // TimeChecker.swift // FastSell // // Created by Nghia Nguyen on 8/24/16. // Copyright © 2016 vn.fastsell. All rights reserved. // import Foundation import RxSwift public final class NKTimeChecker { private(set) var latestSuccessfulCheckingTime: TimeInterval = 0 { didSet { guard let key = self.key else { return } UserDefaults.standard.set(latestSuccessfulCheckingTime, forKey: key) UserDefaults.standard.synchronize() } } let timeInterval: TimeInterval let key: String? public init(timeInterval: TimeInterval, key: String? = nil) { self.timeInterval = timeInterval self.key = key if let key = self.key { self.latestSuccessfulCheckingTime = UserDefaults.standard.double(forKey: key) } } public func checkTime() -> Bool { return NSDate().timeIntervalSince1970 - self.latestSuccessfulCheckingTime >= self.timeInterval } public func checkTimeObservable() -> Observable<Bool> { return Observable.nk_baseCreate({ (observer) in observer.nk_setValue(self.checkTime()) }) } public func updateLatestSuccessfullCheckingTime(time: TimeInterval = NSDate().timeIntervalSince1970) -> Void { self.latestSuccessfulCheckingTime = time } }
mit
migueloruiz/la-gas-app-swift
lasgasmx/CalcResultCell.swift
1
1908
// // CalcResultCell.swift // lasgasmx // // Created by Desarrollo on 4/7/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit class CalcResultCell: CollectionDatasourceCell { override var datasourceItem: Any? { didSet { guard let item = datasourceItem as? CalcPrice else { return } setColor(by: item.price.type) resultLable.text = item.calculate() } } let fuelLabel: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: 18, weight: 500) l.textAlignment = .center l.textColor = .white l.backgroundColor = .clear return l }() let resultLable: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: 18) l.textAlignment = .center l.tintColor = .black l.backgroundColor = .white l.layer.cornerRadius = 10 l.clipsToBounds = true return l }() override func setupViews() { addSubview(fuelLabel) addSubview(resultLable) fuelLabel.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: resultLable.leftAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) resultLable.anchor(top: topAnchor, left: fuelLabel.rightAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 15, leftConstant: 0, bottomConstant: 15, rightConstant: 15, widthConstant: frame.width * 0.6, heightConstant: 0) } func setColor(by type: FuelType) { fuelLabel.text = type.rawValue switch type { case .Magna: self.backgroundColor = UIColor.magna case .Premium: self.backgroundColor = UIColor.premium case .Diesel: self.backgroundColor = UIColor.diesel } } }
mit
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Managers/Launcher/PersistencyCoordinator.swift
1
462
// // PersistencyCoordinator.swift // Rocket.Chat // // Created by Rafael Machado on 11/12/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift struct PersistencyCoordinator: LauncherProtocol { func prepareToLaunch(with options: [UIApplicationLaunchOptionsKey: Any]?) { Realm.Configuration.defaultConfiguration = Realm.Configuration( deleteRealmIfMigrationNeeded: true ) } }
mit
ZhaoBingDong/EasySwifty
EasySwifty/Classes/Easy+CollectionView.swift
1
3087
// // Easy+CollectionView.swift // EaseSwifty // // Created by 董招兵 on 2017/8/6. // Copyright © 2017年 大兵布莱恩特. All rights reserved. // import Foundation import UIKit public extension UICollectionView { // //MARK: Reload Cell // func reload(at item : Int, inSection section : Int) { // reload(at : IndexPath(item: item, section: section)) // } // func reload(at indexPath : IndexPath) { // reloadItems(at: [indexPath]) // } // func reload(atSections section : Int) { // reloadSections(IndexSet(integer: section)) // } // // //MARK: Insert Cell // func insert(at item : Int, inSection section : Int) { // insert(at: IndexPath(item: item, section: section)) // } // func insert(at indexPath : IndexPath) { // insertItems(at: [indexPath]) // } // func insert(atSections section : Int) { // insertSections(IndexSet(integer: section)) // } // // //MARK: Delete Cell // func delete(at item : Int, inSection section : Int) { // delete(at: IndexPath(item: item, section: section)) // } // func delete(at indexPath : IndexPath) { // deleteItems(at: [indexPath]) // } // func delete(atSections section : Int) { // deleteSections(IndexSet(integer: section)) // } // @discardableResult func dequeueReusableCell<T : UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T { guard let cell = self.dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") } return cell } func registerCell<T : UICollectionViewCell>(_ t : T.Type) { if let xib = t.xib { register(xib, forCellWithReuseIdentifier: t.reuseIdentifier) } else { register(t, forCellWithReuseIdentifier: t.reuseIdentifier) } } } /// 添加上拉下拉刷新的 protocol MJCollectionViewRefreshable where Self : UIViewController { var collectionView : UICollectionView { get set } var pageNo : Int { get set} func beginRefresh(_ page : Int) //刷新后 } // //extension MJCollectionViewRefreshable { // // /// 默认实现 下拉刷新 // func addHeaderRefresh() { // self.collectionView.mj_header = MiaoTuHeader(refreshingBlock: { [weak self] in // self?.pageNo = 1 // self?.beginRefresh(self?.pageNo ?? 1) // }) // } // // /// 默认实现 上拉加载更多 // func addFooterRefresh() { // self.collectionView.mj_footer = MiaoTuFooter(refreshingBlock: { [weak self] in // self?.pageNo += 1 // self?.beginRefresh(self?.pageNo ?? 1) // }) // } // // func endRefresh() { // if self.collectionView.mj_header != nil { // self.collectionView.mj_header.endRefreshing() // } // if self.collectionView.mj_footer != nil { // self.collectionView.mj_footer.endRefreshing() // } // } //} // //
apache-2.0
yunhai0417/YHPageViewController
YHPageView/YHPageViewController/YHPageViewHIddenBarDelegate.swift
1
659
// // YHPageViewHIddenBarDelegate.swift // NestiaUser // // Created by 吴云海 on 16/12/26. // Copyright © 2016年 Nestia Pte Ltd. All rights reserved. // navBar 隐藏效果 import UIKit protocol YHPageViewHIddenBarDelegate : class { // 隐藏navBar func changeNavBarStatue(_ scrollview:UIScrollView,_ isHidden:Bool,_ currentOffset:CGFloat) // 获取当前nvBar的状态 func currentNavBarSatue() -> Bool } extension YHPageViewHIddenBarDelegate { func changeNavBarStatue(_ scrollview:UIScrollView,_ isHidden:Bool,_ currentOffset:CGFloat){ } func currentNavBarSatue() -> Bool{ return true } }
mit
tinrobots/Mechanica
Sources/Foundation/NSMutableAttributedString+Utils.swift
1
3812
#if canImport(Foundation) import Foundation extension NSMutableAttributedString { // MARK: - Attributes /// **Mechanica** /// /// Removes all the attributes from `self`. public func removeAllAttributes() { setAttributes([:], range: NSRange(location: 0, length: string.count)) } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString removing all the attributes. public func removingAllAttributes() -> NSMutableAttributedString { return NSMutableAttributedString(string: string) } // MARK: - Operators /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: NSMutableAttributedString) -> NSMutableAttributedString { // swiftlint:disable force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString let rightMutableAttributedString = rhs.mutableCopy() as! NSMutableAttributedString // swiftlint:enable force_cast leftMutableAttributedString.append(rightMutableAttributedString) return leftMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSAttributedString to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: NSAttributedString) -> NSMutableAttributedString { // swiftlint:disable:next force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString // swiftlint:enable force_cast leftMutableAttributedString.append(rhs) return leftMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left NSAttributedString. public static func + (lhs: NSAttributedString, rhs: NSMutableAttributedString) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: lhs) return mutableAttributedString + rhs } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right String to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: String) -> NSMutableAttributedString { // swiftlint:disable:next force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString let rightMutableAttributedString = NSMutableAttributedString(string: rhs) return leftMutableAttributedString + rightMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left String. public static func + (lhs: String, rhs: NSMutableAttributedString) -> NSMutableAttributedString { let leftMutableAttributedString = NSMutableAttributedString(string: lhs) // swiftlint:disable:next force_cast let rightMutableAttributedString = rhs.mutableCopy() as! NSMutableAttributedString return leftMutableAttributedString + rightMutableAttributedString } /// **Mechanica** /// /// Appends the right NSMutableAttributedString to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: NSMutableAttributedString) { lhs.append(rhs) } /// **Mechanica** /// /// Appends the right NSAttributedString to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: NSAttributedString) { lhs.append(rhs) } /// **Mechanica** /// /// Appends the right String to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: String) { lhs.append(NSAttributedString(string: rhs)) } } #endif
mit
mitchellporter/PeriscommentView
PeriscommentView/PeriscommentView.swift
3
2320
// // PeriscommentView.swift // PeriscommentView // // Created by Takuma Yoshida on 2015/04/08. // Copyright (c) 2015 Uniface, Inc. All rights reserved. // import UIKit public class PeriscommentView: UIView { private var visibleCells: [PeriscommentCell] = [] private var config: PeriscommentConfig convenience override init(frame: CGRect) { let config = PeriscommentConfig() self.init(frame: frame, config: config) } required public init(coder aDecoder: NSCoder) { self.config = PeriscommentConfig() super.init(coder: aDecoder) } init(frame: CGRect, config: PeriscommentConfig) { self.config = config super.init(frame: frame) } override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) setupView() } private func setupView() { self.backgroundColor = config.layout.backgroundColor } public func addCell(cell: PeriscommentCell) { cell.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.height), size: cell.frame.size) visibleCells.append(cell) self.addSubview(cell) UIView.animateWithDuration(self.config.appearDuration, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in let dy = cell.frame.height + self.config.layout.cellSpace for c in self.visibleCells { let origin = c.transform let transform = CGAffineTransformMakeTranslation(0, -dy) c.transform = CGAffineTransformConcat(origin, transform) } }, completion: nil) UIView.animateWithDuration(self.config.disappearDuration, delay: self.config.appearDuration, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in cell.alpha = 0.0 }) { (Bool) -> Void in cell.removeFromSuperview() self.visibleCells.removeLast() } } public func addCell(profileImage: UIImage, name: String, comment: String) { let rect = CGRect.zeroRect let cell = PeriscommentCell(frame: rect, profileImage: profileImage, name: name, comment: comment, config: self.config) self.addCell(cell) } }
mit
tgosp/pitch-perfect
PitchPerfect/RecordedAudio.swift
1
392
// // RecordedAudio.swift // PitchPerfect // // Created by Todor Gospodinov on 12/13/15. // Copyright © 2015 Todor Gospodinov. All rights reserved. // import Foundation class RecordedAudio : NSObject { var filePathUrl: NSURL! var title: String! init(filePath: NSURL, audioFileTitle: String) { filePathUrl = filePath title = audioFileTitle } }
mit
noppoMan/Suv
Sources/Suv/Util/RunMode.swift
2
653
// // RunMode.swift // SwiftyLibuv // // Created by Yuki Takei on 6/12/16. // // import CLibUv /** Mode used to run the loop with uv_run() */ public enum RunMode { case runDefault case runOnce case runNoWait } extension RunMode { init(mode: uv_run_mode) { switch mode { case UV_RUN_ONCE: self = .runOnce case UV_RUN_NOWAIT: self = .runNoWait default: self = .runDefault } } public var rawValue: uv_run_mode { switch self { case .runOnce: return UV_RUN_ONCE case .runNoWait: return UV_RUN_NOWAIT default: return UV_RUN_DEFAULT } } }
mit
KrishMunot/swift
test/Generics/slice_test.swift
1
2281
// RUN: %target-parse-verify-swift -parse-stdlib import Swift infix operator < { associativity none precedence 170 } infix operator == { associativity none precedence 160 } infix operator != { associativity none precedence 160 } func testslice(_ s: Array<Int>) { for i in 0..<s.count { print(s[i]+1) } for i in s { print(i+1) } _ = s[0..<2] _ = s[0...1] } @_silgen_name("malloc") func c_malloc(_ size: Int) -> UnsafeMutablePointer<Void> @_silgen_name("free") func c_free(_ p: UnsafeMutablePointer<Void>) class Vector<T> { var length : Int var capacity : Int var base : UnsafeMutablePointer<T> init() { length = 0 capacity = 0 base = nil } func push_back(_ elem: T) { if length == capacity { let newcapacity = capacity * 2 + 2 let size = Int(Builtin.sizeof(T.self)) let newbase = UnsafeMutablePointer<T>(c_malloc(newcapacity * size)) for i in 0..<length { (newbase + i).initialize(with: (base+i).move()) } c_free(base) base = newbase capacity = newcapacity } (base+length).initialize(with: elem) length += 1 } func pop_back() -> T { length -= 1 return (base + length).move() } subscript (i : Int) -> T { get { if i >= length { Builtin.int_trap() } return (base + i).pointee } set { if i >= length { Builtin.int_trap() } (base + i).pointee = newValue } } deinit { for i in 0..<length { (base + i).deinitialize() } c_free(base) } } protocol Comparable { func <(lhs: Self, rhs: Self) -> Bool } func sort<T : Comparable>(_ array: inout [T]) { for i in 0..<array.count { for j in i+1..<array.count { if array[j] < array[i] { let temp = array[i] array[i] = array[j] array[j] = temp } } } } func find<T : Eq>(_ array: [T], value: T) -> Int { var idx = 0 for elt in array { if (elt == value) { return idx } idx += 1 } return -1 } func findIf<T>(_ array: [T], fn: (T) -> Bool) -> Int { var idx = 0 for elt in array { if (fn(elt)) { return idx } idx += 1 } return -1 } protocol Eq { func ==(lhs: Self, rhs: Self) -> Bool func !=(lhs: Self, rhs: Self) -> Bool }
apache-2.0
KrishMunot/swift
test/SILOptimizer/no_opt.swift
6
483
// RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s func bar(_ x : Int) { } // CHECK-LABEL: _TF6no_opt4foo1FT_T_ // CHECK-NOT: integer_literal // CHECK: return public func foo1() { bar(1) bar(2) bar(3) bar(4) } // CHECK-LABEL: _TF6no_opt4foo2FT_T_ // CHECK: integer_literal // CHECK: integer_literal // CHECK: integer_literal // CHECK: integer_literal // CHECK: return @_semantics("optimize.sil.never") public func foo2() { bar(1) bar(2) bar(3) bar(4) }
apache-2.0
apple/swift-tools-support-core
Tests/TSCBasicTests/CollectionExtensionsTests.swift
1
837
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic class CollectionExtensionsTests: XCTestCase { func testOnly() { XCTAssertEqual([String]().spm_only, nil) XCTAssertEqual([42].spm_only, 42) XCTAssertEqual([42, 24].spm_only, nil) } func testUniqueElements() { XCTAssertEqual([1, 2, 2, 4, 2, 1, 1, 4].spm_uniqueElements(), [1, 2, 4]) XCTAssertEqual([1, 2, 2, 4, 2, 1, 1, 4, 9].spm_uniqueElements(), [1, 2, 4, 9]) XCTAssertEqual([3, 2, 1].spm_uniqueElements(), [3, 2, 1]) } }
apache-2.0
connienguyen/volunteers-iOS
VOLA/VOLA/Helpers/Extensions/UIKit/UIViewController.swift
1
5898
// // UIViewController.swift // VOLA // // Created by Connie Nguyen on 6/6/17. // Copyright © 2017 Systers-Opensource. All rights reserved. // import UIKit // Apply StoryboardIdentifiable protocol to all UIViewControllers extension UIViewController: StoryboardIdentifiable {} extension UIViewController { /** Perform one of available segues - Parameters: - segue: Segue to perform */ func performSegue(_ segue: Segue, sender: Any?) { performSegue(withIdentifier: segue.identifier, sender: sender) } /// Currently active indicator, nil if there is no indicator var currentActivityIndicator: UIActivityIndicatorView? { return view.subviews.first(where: { $0 is UIActivityIndicatorView }) as? UIActivityIndicatorView } /// Display activity indicator if there is not one already active func displayActivityIndicator() { guard currentActivityIndicator == nil else { // Make sure there isn't already an activity indicator Logger.error(UIError.existingActivityIndicator) return } let indicator = UIActivityIndicatorView(frame: view.frame) indicator.activityIndicatorViewStyle = .gray indicator.center = view.center indicator.backgroundColor = ThemeColors.lightGrey indicator.isHidden = false indicator.startAnimating() self.view.addSubview(indicator) } /// Remove current activity indicator if there is one func removeActivityIndicator() { if let indicator = currentActivityIndicator { indicator.removeFromSuperview() } } /** Display error in an alert view controller - Parameters: - errorTitle: Title to display on error alert - errorMessage: Message to display on error alert */ func showErrorAlert(errorTitle: String, errorMessage: String) { let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: DictKeys.ok.rawValue, style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } /// Current login upsell view if there is one var loginUpsellView: LoginUpsellView? { return view.subviews.first(where: {$0 is LoginUpsellView }) as? LoginUpsellView } /** Shows login upsell view if there is already not one on the view controller and sets up target for the button on the upsell */ func showUpsell() { // Guard against showing multiple upsells on the same view controller guard loginUpsellView == nil else { return } let newUpsell = LoginUpsellView.instantiateFromXib() let viewFrame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) newUpsell.frame = viewFrame newUpsell.layer.zPosition += 1 newUpsell.loginButton.addTarget(self, action: #selector(presentLoginFromUpsell), for: .touchUpInside) view.addSubview(newUpsell) addNotificationObserver(NotificationName.userLogin, selector: #selector(removeUpsell)) } /// Remove login upsell if there is one active on view controller func removeUpsell() { // Guard against removing upsell view from view controller when there is none guard let upsellView = loginUpsellView else { return } upsellView.removeFromSuperview() removeNotificationObserver(NotificationName.userLogin) } /// Present login flow where use can log in through a social network or manually with email func presentLoginFromUpsell() { let loginNavVC: LoginNavigationController = UIStoryboard(.login).instantiateViewController() present(loginNavVC, animated: true, completion: nil) } /** Show alert that user can dismiss or use as a shortcut to the login flow in order to complete an action that requires a user account (e.g. event registration) */ func showLoginAlert() { let alert = UIAlertController(title: UIDisplay.loginRequiredTitle.localized, message: UIDisplay.loginRequiredPrompt.localized, preferredStyle: .alert) let loginAction = UIAlertAction(title: UIDisplay.loginPrompt.localized, style: .default) { _ in let loginNavVC: LoginNavigationController = UIStoryboard(.login).instantiateViewController() self.present(loginNavVC, animated: true, completion: nil) } let cancelAction = UIAlertAction(title: UIDisplay.cancel.localized, style: .cancel, handler: nil) alert.addAction(loginAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } /** Show alert that user can dismiss or use as a shortcut to Settings to edit app permissions - Parameters: - title: Title of the alert (suggested to use title of permission that needs access) - message: Message of the alert (suggested to use an explaination for permission access) */ func showEditSettingsAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let openSettingsAction = UIAlertAction(title: UIDisplay.editSettings.localized, style: .default, handler: { (_) in guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else { return } URL.applicationOpen(url: settingsURL) }) let cancelAction = UIAlertAction(title: UIDisplay.cancel.localized, style: .cancel, handler: nil) alert.addAction(openSettingsAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } }
gpl-2.0
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/SettingsFeature/SettingsView.swift
1
7473
import AcknowList import ComposableArchitecture import Helpers import L10n import Styleguide import SwiftUI import SwiftUIHelpers /// A view to render the app settings. public struct SettingsView: View { public typealias State = SettingsFeature.State public typealias Action = SettingsFeature.Action @Environment(\.colorSchemeContrast) var colorSchemeContrast let store: Store<State, Action> @ObservedObject var viewStore: ViewStore<State, Action> public init(store: Store<State, Action>) { self.store = store viewStore = ViewStore(store, removeDuplicates: ==) } public var body: some View { SettingsForm { Spacer(minLength: 28) VStack { SettingsSection(title: "") { SettingsNavigationLink( destination: RideEventSettingsView( store: store.scope( state: \.userSettings.rideEventSettings, action: SettingsFeature.Action.rideevent ) ), title: L10n.Settings.eventSettings ) SettingsRow { observationModeRow .accessibilityValue( viewStore.userSettings.enableObservationMode ? Text(L10n.A11y.General.on) : Text(L10n.A11y.General.off) ) .accessibilityAction { viewStore.send(.setObservationMode(!viewStore.userSettings.enableObservationMode)) } } SettingsNavigationLink( destination: AppearanceSettingsView( store: store.scope( state: \SettingsFeature.State.userSettings.appearanceSettings, action: SettingsFeature.Action.appearance ) ), title: L10n.Settings.Theme.appearance ) } supportSection infoSection } } .navigationTitle(L10n.Settings.title) .frame( maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading ) .onAppear { viewStore.send(.onAppear) } } var observationModeRow: some View { HStack { VStack(alignment: .leading, spacing: .grid(1)) { Text(L10n.Settings.Observationmode.title) .font(.titleOne) Text(L10n.Settings.Observationmode.detail) .foregroundColor(colorSchemeContrast.isIncreased ? Color(.textPrimary) : Color(.textSilent)) .font(.bodyOne) } Spacer() Toggle( isOn: viewStore.binding( get: { $0.userSettings.enableObservationMode }, send: SettingsFeature.Action.setObservationMode ), label: { EmptyView() } ) .labelsHidden() } .accessibilityElement(children: .combine) } var supportSection: some View { SettingsSection(title: L10n.Settings.support) { VStack(alignment: .leading, spacing: .grid(4)) { Button( action: { viewStore.send(.supportSectionRowTapped(.github)) }, label: { SupportSettingsRow( title: L10n.Settings.programming, subTitle: L10n.Settings.Opensource.detail, link: L10n.Settings.Opensource.action, textStackForegroundColor: Color(.textPrimaryLight), backgroundColor: Color(.brand500), bottomImage: Image(uiImage: Asset.ghLogo.image) ) } ) .accessibilityAddTraits(.isLink) Button( action: { viewStore.send(.supportSectionRowTapped(.crowdin)) }, label: { SupportSettingsRow( title: L10n.Settings.Translate.title, subTitle: L10n.Settings.Translate.subtitle, link: L10n.Settings.Translate.link, textStackForegroundColor: .white, backgroundColor: Color(.translateRowBackground), bottomImage: Image(uiImage: Asset.translate.image) ) } ) .accessibilityAddTraits(.isLink) Button( action: { viewStore.send(.supportSectionRowTapped(.criticalMassDotIn)) }, label: { SupportSettingsRow( title: L10n.Settings.CriticalMassDotIn.title, subTitle: L10n.Settings.CriticalMassDotIn.detail, link: L10n.Settings.CriticalMassDotIn.action, textStackForegroundColor: Color(.textPrimaryLight), backgroundColor: Color(.cmInRowBackground), bottomImage: Image(uiImage: Asset.cmDotInLogo.image) ) } ) .accessibilityAddTraits(.isLink) } .padding(.horizontal, .grid(4)) } } var infoSection: some View { SettingsSection(title: L10n.Settings.Section.info) { SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.website)) }, label: { SettingsInfoLink(title: L10n.Settings.website) } ) .accessibilityAddTraits(.isLink) } SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.twitter)) }, label: { SettingsInfoLink(title: L10n.Settings.twitter) } ) .accessibilityAddTraits(.isLink) } SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.privacy)) }, label: { SettingsInfoLink(title: L10n.Settings.privacyPolicy) } ) .accessibilityAddTraits(.isLink) } if let acknowledgementsPlistPath = viewStore.acknowledgementsPlistPath { SettingsNavigationLink( destination: AcknowListSwiftUIView(plistPath: acknowledgementsPlistPath), title: "Acknowledgements" ) } appVersionAndBuildView } } var appVersionAndBuildView: some View { HStack(spacing: .grid(4)) { ZStack { RoundedRectangle(cornerRadius: 12.5) .foregroundColor(.white) .frame(width: 56, height: 56, alignment: .center) .overlay( RoundedRectangle(cornerRadius: 12.5) .strokeBorder(Color(.border), lineWidth: 1) ) Image(uiImage: Asset.cmLogoC.image) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 48, height: 48, alignment: .center) } .accessibilityHidden(true) VStack(alignment: .leading) { Text(viewStore.versionNumber) .font(.titleTwo) .foregroundColor(Color(.textPrimary)) Text(viewStore.buildNumber) .font(.bodyTwo) .foregroundColor(colorSchemeContrast.isIncreased ? Color(.textPrimary) : Color(.textSilent)) } .accessibilityElement(children: .combine) } .padding(.grid(4)) } } struct SettingsInfoLink: View { let title: String var body: some View { HStack { Text(title) .font(.titleOne) Spacer() Image(systemName: "arrow.up.right") .font(.titleOne) .accessibilityHidden(true) } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { Preview { NavigationView { SettingsView( store: .init( initialState: .init(), reducer: SettingsFeature()._printChanges() ) ) } } } }
mit
khizkhiz/swift
test/SourceKit/Demangle/demangle.swift
8
728
// RUN: %sourcekitd-test -req=demangle unmangled _TtBf80_ _TtP3foo3bar_ | FileCheck %s // CHECK: START DEMANGLE // CHECK-NEXT: <empty> // CHECK-NEXT: Builtin.Float80 // CHECK-NEXT: foo.bar // CHECK-NEXT: END DEMANGLE // RUN: %sourcekitd-test -req=demangle unmangled _TtBf80_ _TtP3foo3bar_ -simplified-demangling | FileCheck %s -check-prefix=SIMPLIFIED // SIMPLIFIED: START DEMANGLE // SIMPLIFIED-NEXT: <empty> // SIMPLIFIED-NEXT: Builtin.Float80 // SIMPLIFIED-NEXT: bar // SIMPLIFIED-NEXT: END DEMANGLE // RUN: %sourcekitd-test -req=mangle Foo.Baru Swift.Beer | FileCheck %s -check-prefix=MANGLED // MANGLED: START MANGLE // MANGLED-NEXT: _TtC3Foo4Baru // MANGLED-NEXT: _TtCs4Beer // MANGLED-NEXT: END MANGLE
apache-2.0
Mindera/Alicerce
Tests/AlicerceTests/Utils/TokenTests.swift
1
1705
import XCTest @testable import Alicerce class TokenTests: XCTestCase { func testNext_ShouldGenerateUniqueTokens() { let tokenizer = Tokenizer<()>() let tokens = (0..<100).map { _ in tokenizer.next } let set = Set(tokens) XCTAssertEqual(tokens.count, set.count) } func testNext_ShouldGenerateTheSameSequenceWithDifferentTokenizers() { let tokenizer1 = Tokenizer<Int>() let tokenizer2 = Tokenizer<Int>() let tokens1 = (0..<100).map { _ in tokenizer1.next } let tokens2 = (0..<100).map { _ in tokenizer2.next } XCTAssertEqual(tokens1, tokens2) } func testNext_ShouldHandleConcurrentAccesses() { let count: (accesses: Int, queues: Int) = (100, 4) let queues: [OperationQueue] = (0..<count.queues).map { _ in let queue = OperationQueue() queue.isSuspended = true return queue } let tokenizer = Tokenizer<Int>() let tokens = Atomic<[Token<Int>]>([]) let expectation = self.expectation(description: "token") expectation.expectedFulfillmentCount = count.accesses * count.queues (0..<count.accesses).forEach { _ in queues.forEach { $0.addOperation { let token = tokenizer.next tokens.modify { $0.append(token) } expectation.fulfill() } } } queues.forEach { $0.isSuspended = false } waitForExpectations(timeout: 1) XCTAssertEqual(tokens.value.count, count.accesses * count.queues) XCTAssertEqual(Set(tokens.value).count, tokens.value.count) } }
mit
ParsaTeam/track-manager-ios
TrackManager/TrackManager.swift
1
2052
// // TrackManager.swift // TrackManager // // Created by Thiago Magalhães on 22/02/17. // Copyright © 2017 NET. All rights reserved. // import Foundation @objc public final class TrackManager: NSObject { //MARK: Singleton override private init() { } public static let shared = TrackManager() //MARK: Properties public var showLogs = true private var connectors: [Connector] = [] //MARK: Tracking methods public func track(_ trackable: Trackable, excluding: [String] = []) { DispatchQueue.global(qos: .background).async { for connector in self.connectors { if !excluding.contains(connector.id()) { connector.track(trackable) self.log("Event sent to connector with id \"\(connector.id())\"") } } } } //MARK: Connector handling methods public func add(_ connector: Connector) { guard (self.connectors.index { $0 == connector }) == nil else { log("Connector with id \"\(connector.id())\" already added") return } self.connectors.append(connector) log("Added connector with id \"\(connector.id())\"") } func remove(_ connector: Connector) { if let index = (self.connectors.index { $0 == connector }) { self.connectors.remove(at: index) log("Removed connector with id \"\(connector.id())\"") } else { log("Connector with id \"\(connector.id())\" not found") } } //MARK: Logging methods private func log(_ text: String) { guard self.showLogs else { return } print(text) } } func ==(lhs: Connector, rhs: Connector) -> Bool { return lhs.id() == rhs.id() }
mit
PiXeL16/BudgetShare
BudgetShareTests/Modules/SignUp/Interactor/SignUpInteractorSpec.swift
1
1634
import Nimble import Quick @testable import BudgetShare class SignUpInteractorSpec: QuickSpec { override func spec() { describe("The signUp interactor provider") { var subject: SignUpInteractorProvider! var service: MockAuthenticationService! var output: MockSignUpInteractorOutput! beforeEach { service = MockAuthenticationService() output = MockSignUpInteractorOutput() subject = SignUpInteractorProvider(service: service) subject.output = output } it("Inits with correct values") { expect(subject.service).toNot(beNil()) expect(subject.output).toNot(beNil()) } it("SignUp succesfully") { subject.signUp(email: "[email protected]", password: "test", name: "test") expect(output.signUpSucceedCalled).to(beTrue()) expect(output.user).toNot(beNil()) expect(output.authenticationError).to(beNil()) } it("SignUp Failed") { service.signUpShouldSucceed = false subject.signUp(email: "[email protected]", password: "test", name: "test") expect(output.signUpFailedCalled).to(beTrue()) expect(output.user).to(beNil()) expect(output.authenticationError).toNot(beNil()) } } } }
mit
yyny1789/KrMediumKit
Source/Network/NetworkManager.swift
1
7965
// // NetworkManager.swift // Client // // Created by aidenluo on 7/26/16. // Copyright © 2016 36Kr. All rights reserved. // import Foundation import Moya import ObjectMapper import ReachabilitySwift import AdSupport public final class NetworkManager { public class var manager: NetworkManager { struct SingletonWrapper { static let singleton = NetworkManager() } return SingletonWrapper.singleton } public let userAgent: String = NetworkManagerSettings.userAgent ?? "未设置 ua" fileprivate var customHTTPHeader: [String: String] { return NetworkManagerSettings.customHTTPHeader ?? ["User-Agent": userAgent] } public let reachability: Reachability? = { return Reachability() }() public func requestCacheAPI<T: TargetType, O: Mappable>( _ target: T, ignoreCache: Bool = true, loadCacheFirstWhenIgnoreCache: Bool = true, stub: Bool = false, log: Bool = true, success: @escaping (_ result: O, _ dataFromCache: Bool) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { let url = target.baseURL.appendingPathComponent(target.path).absoluteString if ignoreCache { if loadCacheFirstWhenIgnoreCache { if let cache = DatabaseManager.manager.objectWithPrimaryKey(NetworkCacheEntity.self, primaryKey: url as AnyObject)?.cacheData { if let JSONString = NSString(data: cache, encoding: String.Encoding.utf8.rawValue), let result = Mapper<O>().map(JSONObject: JSONString) { success(result, true) } } } return request(target, stub: stub, log: log, success: { (result: O) in DatabaseManager.manager.saveObjects({ () -> [NetworkCacheEntity] in let cache = NetworkCacheEntity() cache.cacheName = url cache.cacheData = result.toJSONString()?.data(using: String.Encoding.utf8) return [cache] }) success(result, false) }, failure: failure) } else { if let cache = DatabaseManager.manager.objectWithPrimaryKey(NetworkCacheEntity.self, primaryKey: url as AnyObject)?.cacheData { if let JSONString = NSString(data: cache, encoding: String.Encoding.utf8.rawValue), let result = Mapper<O>().map(JSONObject: JSONString) { success(result, true) } else { failure(MoyaError.underlying(NSError(domain: "NetworkManager", code: 1, userInfo: [NSLocalizedDescriptionKey : "缓存的JSON字符串Map至对象失败"]))) } return nil } else { return request(target, stub: stub, log: log, success: { (result: O) in DatabaseManager.manager.saveObjects({ () -> [NetworkCacheEntity] in let cache = NetworkCacheEntity() cache.cacheName = url cache.cacheData = result.toJSONString()?.data(using: String.Encoding.utf8) return [cache] }) success(result, false) }, failure: failure) } } } public func request<T: TargetType, O: Mappable>(_ target: T, stub: Bool = false, log: Bool = true, success: @escaping (_ result: O) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { var provider: MoyaProvider<T> if NetworkManagerSettings.consolelogEnable && log { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub), plugins: [NetworkLoggerPlugin(verbose: true)]) } else { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub)) } return provider.request(target, completion: { (result) in switch result { case .success(let response): do { if response.statusCode == 200 { let JSON = try response.mapJSON() as? NSDictionary if let code = JSON?["code"] as? Int, let loseCode = NetworkManagerSettings.loseLoginStatusCode, code == loseCode { NetworkManagerSettings.loseLoginStatusHandle() return } let mapper = Mapper<O>() if let object = mapper.map(JSONObject: JSON) { success(object) } else { failure(MoyaError.jsonMapping(response)) } } else { failure(MoyaError.statusCode(response)) } } catch { failure(MoyaError.jsonMapping(response)) } case .failure(let error): failure(error) } }) } public func request<T: TargetType>(_ target: T, stub: Bool = false, log: Bool = true, success: @escaping (_ result: Data) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { var provider: MoyaProvider<T> if NetworkManagerSettings.consolelogEnable && log { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub), plugins: [NetworkLoggerPlugin(verbose: true)]) } else { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub)) } return provider.request(target, completion: { (result) in switch result { case .success(let response): if response.statusCode == 200 { success(response.data) } else { failure(MoyaError.statusCode(response)) } case .failure(let error): failure(error) } }) } fileprivate func endpointGenerator<T: TargetType>() -> (_ target: T) -> Endpoint<T> { let generator = { (target: T) -> Endpoint<T> in let URL = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint: Endpoint<T> = Endpoint<T>(url: URL, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) return endpoint.adding(newHTTPHeaderFields: self.customHTTPHeader) } return generator } fileprivate func stubGenerator<T>(_ stub: Bool) -> (_ target: T) -> StubBehavior { let stubClosure = { (target: T) -> StubBehavior in if stub { return .immediate } else { return .never } } return stubClosure } public func generalRequest<T: TargetType>(_ target: T, completion: @escaping Completion) -> Cancellable? { let endpointClosure = { (target: T) -> Endpoint<T> in let URL = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint: Endpoint<T> = Endpoint<T>(url: URL, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) return endpoint.adding(newHTTPHeaderFields: self.customHTTPHeader) } let provider = MoyaProvider<T>(endpointClosure: endpointClosure) return provider.request(target, completion: completion) } }
mit
Ryce/Convrt
Convrt/Convrt/AppDelegate.swift
1
3106
// // AppDelegate.swift // Convrt // // Created by Hamon Riazy on 16/05/15. // Copyright (c) 2015 ryce. 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:. } @available(iOS 9.0, *) func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { print("shortcut call") if shortcutItem.type == "com.ryce.convrt.openhundredeur" { guard let viewController = self.window?.rootViewController as? ViewController, let shortcutCurrency = shortcutItem.userInfo?["currency"] as? String, let currency = ConvrtSession.sharedInstance.savedCurrencyConfiguration.filter({ $0.code == shortcutCurrency }).first, let shortcutAmount = shortcutItem.userInfo?["amount"] as? String, let currentAmount = Double(shortcutAmount) else { completionHandler(false) return } viewController.updateView(currentAmount, currency: currency) } completionHandler(true) } }
gpl-2.0
ming1016/smck
smck/Lib/RxSwift/BehaviorSubject.swift
15
4343
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a value that changes over time. /// /// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , SynchronizedUnsubscribeType , Disposable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType /// Indicates whether the subject has any observers public var hasObservers: Bool { _lock.lock() let value = _observers.count > 0 _lock.unlock() return value } let _lock = RecursiveLock() // state private var _isDisposed = false private var _value: Element private var _observers = Bag<(Event<Element>) -> ()>() private var _stoppedEvent: Event<Element>? /// Indicates whether the subject has been disposed. public var isDisposed: Bool { return _isDisposed } /// Initializes a new instance of the subject that caches its last value and starts with the specified value. /// /// - parameter value: Initial value sent to observers when no other value has been received by the subject yet. public init(value: Element) { _value = value } /// Gets the current value or throws an error. /// /// - returns: Latest value. public func value() throws -> Element { _lock.lock(); defer { _lock.unlock() } // { if _isDisposed { throw RxError.disposed(object: self) } if let error = _stoppedEvent?.error { // intentionally throw exception throw error } else { return _value } //} } /// Notifies all subscribed observers about next event. /// /// - parameter event: Event to send to the observers. public func on(_ event: Event<E>) { _lock.lock() dispatch(_synchronized_on(event), event) _lock.unlock() } func _synchronized_on(_ event: Event<E>) -> Bag<(Event<Element>) -> ()> { if _stoppedEvent != nil || _isDisposed { return Bag() } switch event { case .next(let value): _value = value case .error, .completed: _stoppedEvent = event } return _observers } /// Subscribes an observer to the subject. /// /// - parameter observer: Observer to subscribe to the subject. /// - returns: Disposable object that can be used to unsubscribe the observer from the subject. public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock() let subscription = _synchronized_subscribe(observer) _lock.unlock() return subscription } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if _isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } let key = _observers.insert(observer.on) observer.on(.next(_value)) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() _synchronized_unsubscribe(disposeKey) _lock.unlock() } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { if _isDisposed { return } _ = _observers.removeKey(disposeKey) } /// Returns observer interface for subject. public func asObserver() -> BehaviorSubject<Element> { return self } /// Unsubscribe all observers and release resources. public func dispose() { _lock.lock() _isDisposed = true _observers.removeAll() _stoppedEvent = nil _lock.unlock() } }
apache-2.0
overtake/TelegramSwift
Telegram-Mac/ChatListMessageRowItem.swift
1
890
// // ChatListMessageRowItem.swift // Telegram-Mac // // Created by keepcoder on 11/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox class ChatListMessageRowItem: ChatListRowItem { init(_ initialSize:NSSize, context: AccountContext, message: Message, id: EngineChatList.Item.Id, query: String, renderedPeer:RenderedPeer, readState: CombinedPeerReadState?, mode: ChatListRowItem.Mode, titleMode: ChatListRowItem.TitleMode) { super.init(initialSize, context: context, stableId: .chatId(id, message.id.peerId, message.id.id), mode: mode, messages: [message], readState: .init(state: readState, isMuted: false), renderedPeer: .init(renderedPeer), highlightText: query, showBadge: false, titleMode: titleMode) } override var stableId: AnyHashable { return message!.id } }
gpl-2.0
mikekavouras/Glowb-iOS
Glowb/Views/Cells/CollectionView/AddInteractionCollectionViewCell.swift
1
399
// // AddInteractionCollectionViewCell.swift // Glowb // // Created by Michael Kavouras on 12/8/16. // Copyright © 2016 Michael Kavouras. All rights reserved. // import UIKit class AddInteractionCollectionViewCell: BaseCollectionViewCell, ReusableView { static var identifier: String = "AddInteractionCellIdentifier" static var nibName: String = "AddInteractionCollectionViewCell" }
mit
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/Connect View Controllers/CustomRaceViewController/CustomRaceNumericalViewController.swift
2
7663
// // CustomRaceNumericalViewController.swift // WikiRaces // // Created by Andrew Finke on 5/3/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import UIKit import WKRKit final class CustomRaceNumericalViewController: CustomRaceController { // MARK: - Types - private class Cell: UITableViewCell { // MARK: - Properties - static let reuseIdentifier = "reuseIdentifier" let stepper = UIStepper() let valueLabel: UILabel = { let label = UILabel() label.textAlignment = .right return label }() // MARK: - Initalization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(stepper) contentView.addSubview(valueLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - override func layoutSubviews() { super.layoutSubviews() stepper.center = CGPoint( x: contentView.frame.width - contentView.layoutMargins.right - stepper.frame.width / 2, y: contentView.frame.height / 2) let labelX = stepper.frame.minX - stepper.layoutMargins.left * 2 valueLabel.frame = CGRect( x: labelX - 50, y: 0, width: 50, height: frame.height) } } enum SettingsType { case points, timing } // MARK: - Properties - var points: WKRGameSettings.Points? { didSet { guard let value = points else { fatalError() } didUpdatePoints?(value) } } var timing: WKRGameSettings.Timing? { didSet { guard let value = timing else { fatalError() } didUpdateTiming?(value) } } var didUpdatePoints: ((WKRGameSettings.Points) -> Void)? var didUpdateTiming: ((WKRGameSettings.Timing) -> Void)? let type: SettingsType // MARK: - Initalization - init(settingsType: SettingsType, currentValue: Any) { self.type = settingsType super.init(style: .grouped) switch type { case .points: guard let points = currentValue as? WKRGameSettings.Points else { fatalError() } self.points = points title = "Points".uppercased() case .timing: guard let timing = currentValue as? WKRGameSettings.Timing else { fatalError() } self.timing = timing title = "Timing".uppercased() } tableView.allowsSelection = false tableView.register(Cell.self, forCellReuseIdentifier: Cell.reuseIdentifier) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return type == .points ? "Bonus Points" : nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else { fatalError() } cell.stepper.tag = indexPath.row cell.stepper.addTarget(self, action: #selector(stepperChanged(stepper:)), for: .valueChanged) switch type { case .points: guard let points = points else { fatalError() } if indexPath.row == 0 { cell.textLabel?.text = "Award Interval" cell.stepper.minimumValue = 5 cell.stepper.maximumValue = 360 cell.stepper.stepValue = 5 cell.stepper.value = points.bonusPointsInterval cell.valueLabel.text = Int(points.bonusPointsInterval).description + " S" } else { cell.textLabel?.text = "Award Amount" cell.stepper.minimumValue = 0 cell.stepper.maximumValue = 20 cell.stepper.stepValue = 1 cell.stepper.value = Double(points.bonusPointReward) cell.valueLabel.text = points.bonusPointReward.description } case .timing: guard let timing = timing else { fatalError() } if indexPath.row == 0 { cell.textLabel?.text = "Voting Time" cell.stepper.minimumValue = 5 cell.stepper.maximumValue = 120 cell.stepper.stepValue = 1 cell.stepper.value = Double(timing.votingTime) cell.valueLabel.text = timing.votingTime.description + " S" } else { cell.textLabel?.text = "Results Time" cell.stepper.minimumValue = 15 cell.stepper.maximumValue = 360 cell.stepper.stepValue = 5 cell.stepper.value = Double(timing.resultsTime) cell.valueLabel.text = timing.resultsTime.description + " S" } } return cell } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if type == .points { let title = """ The award interval is the frequency at which bonus points are added to the total points awarded. If set to 60, then every 60 seconds, the total points awarded to the race winner will increase by the amount specified. Stats Effect: Prevents improving points per race average and total number of races. """ return title } else { return nil } } // MARK: - Helpers - @objc func stepperChanged(stepper: UIStepper) { let indexPath = IndexPath(row: stepper.tag, section: 0) guard let cell = tableView.cellForRow(at: indexPath) as? Cell else { fatalError() } switch type { case .points: guard let points = points else { fatalError() } if indexPath.row == 0 { self.points = WKRGameSettings.Points( bonusPointReward: points.bonusPointReward, bonusPointsInterval: stepper.value) cell.valueLabel.text = Int(stepper.value).description + " S" } else { self.points = WKRGameSettings.Points( bonusPointReward: Int(stepper.value), bonusPointsInterval: points.bonusPointsInterval) cell.valueLabel.text = Int(stepper.value).description } case .timing: guard let timing = timing else { fatalError() } if indexPath.row == 0 { self.timing = WKRGameSettings.Timing( votingTime: Int(stepper.value), resultsTime: timing.resultsTime) cell.valueLabel.text = Int(stepper.value).description + " S" } else { self.timing = WKRGameSettings.Timing( votingTime: timing.votingTime, resultsTime: Int(stepper.value)) cell.valueLabel.text = Int(stepper.value).description + " S" } } } }
mit
huangboju/Moots
Examples/CIFilter/MetalFilters-master/MetalFilters/MTFilter/MTLuxBlendFilter.swift
1
353
// // MTLuxBlendFilter.swift // MetalFilters // // Created by xu.shuifeng on 2018/6/13. // Copyright © 2018 shuifeng.me. All rights reserved. // import Foundation class MTLuxBlendFilter: MTFilter { var luxBlendAmount: Float = 0 override var parameters: [String : Any] { return ["luxBlendAmount": luxBlendAmount] } }
mit
mrdepth/EVEUniverse
Legacy/Neocom/Neocom II Tests/Skills_Tests.swift
2
2070
// // Skills_Tests.swift // Neocom II Tests // // Created by Artem Shimanski on 10/26/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import XCTest @testable import Neocom import EVEAPI import Futures class Skills_Tests: TestCase { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSkillQueue() { let exp = expectation(description: "end") let skillPlan = Services.storage.viewContext.currentAccount?.activeSkillPlan let controller = try! SkillQueue.default.instantiate().get() controller.loadViewIfNeeded() controller.presenter.interactor = SkillQueueInteractorMock(presenter: controller.presenter) controller.viewWillAppear(true) controller.viewDidAppear(true) DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { let type = Services.sde.viewContext.invType("Navigation")! let tq = TrainingQueue(character: controller.presenter.content!.value) tq.add(type, level: 1) skillPlan?.add(tq) try! Services.storage.viewContext.save() DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { exp.fulfill() } } wait(for: [exp], timeout: 10) } } class SkillQueueInteractorMock: SkillQueueInteractor { override func load(cachePolicy: URLRequest.CachePolicy) -> Future<SkillQueueInteractor.Content> { var character = Neocom.Character.empty let skill = Neocom.Character.Skill(type: Services.sde.viewContext.invType("Navigation")!)! let queuedSkill = ESI.Skills.SkillQueueItem.init(finishDate: Date.init(timeIntervalSinceNow: 60), finishedLevel: 1, levelEndSP: skill.skillPoints(at: 1), levelStartSP: 0, queuePosition: 0, skillID: skill.typeID, startDate: Date.init(timeIntervalSinceNow: -60), trainingStartSP: 0) character.skillQueue.append(Neocom.Character.SkillQueueItem(skill: skill, queuedSkill: queuedSkill)) let result = ESI.Result(value: character, expires: nil, metadata: nil) return .init(result) } }
lgpl-2.1
bcesur/FitPocket
FitPocket/FitPocket/ChronometerViewController.swift
1
3046
// // ChronometerViewController.swift // FitPocket // // Created by Berkay Cesur on 23/12/14. // Copyright (c) 2014 Berkay Cesur. All rights reserved. // import UIKit class ChronometerViewController: UIViewController { @IBOutlet weak var cmLabel: UILabel! @IBAction func backButtonTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } var startTime = NSTimeInterval() var timer: NSTimer = NSTimer() var elapsedTime = NSTimeInterval() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { } @IBAction func pauseButtonTapped() { //timer = NSTimer.scheduledTimerWithTimeInterval(0.00, target: self, selector: "sacmasapan", userInfo: nil, repeats: false) } @IBAction func resetButtonTapped() { timer.invalidate() cmLabel.text = "00:00:00" timer = nil } @IBAction func startButtonTapped() { if (!timer.valid) { timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true) startTime = NSDate.timeIntervalSinceReferenceDate() } } func updateTime() { var currentTime = NSDate.timeIntervalSinceReferenceDate() //Find the difference between current time and start time. elapsedTime = currentTime - startTime //calculate the minutes in elapsed time. let minutes = UInt8(elapsedTime / 60.0) elapsedTime -= (NSTimeInterval(minutes) * 60) //calculate the seconds in elapsed time. let seconds = UInt8(elapsedTime) elapsedTime -= NSTimeInterval(seconds) //find out the fraction of milliseconds to be displayed. let fraction = UInt8(elapsedTime * 100) //add the leading zero for minutes, seconds and millseconds and store them as string constants let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes) let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds) let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction) //concatenate minuets, seconds and milliseconds as assign it to the UILabel cmLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Custom Class/AMAVPlayerItem.swift
1
1904
import AVFoundation // MARK: - Responsible for handling the KVO operations that happen on the AVPlayerItem. public enum AwesomeMediaPlayerItemKeyPaths: String { case playbackLikelyToKeepUp case playbackBufferFull case playbackBufferEmpty case status case timeControlStatus } public class AMAVPlayerItem: AVPlayerItem { private var observersKeyPath = [String: NSObject?]() private var keysPathArray: [AwesomeMediaPlayerItemKeyPaths] = [.playbackLikelyToKeepUp, .playbackBufferFull, .playbackBufferEmpty, .status, .timeControlStatus] deinit { for (keyPath, observer) in observersKeyPath { if let observer = observer { self.removeObserver(observer, forKeyPath: keyPath) } } } override public func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) { super.addObserver(observer, forKeyPath: keyPath, options: options, context: context) if let keyPathRaw = AwesomeMediaPlayerItemKeyPaths(rawValue: keyPath), keysPathArray.contains(keyPathRaw) { if let obj = observersKeyPath[keyPath] as? NSObject { self.removeObserver(obj, forKeyPath: keyPath) observersKeyPath[keyPath] = observer } else { observersKeyPath[keyPath] = observer } } } override public func removeObserver(_ observer: NSObject, forKeyPath keyPath: String, context: UnsafeMutableRawPointer?) { super.removeObserver(observer, forKeyPath: keyPath, context: context) observersKeyPath[keyPath] = nil } public override func removeObserver(_ observer: NSObject, forKeyPath keyPath: String) { super.removeObserver(observer, forKeyPath: keyPath) observersKeyPath[keyPath] = nil } }
mit
starhoshi/pi-chan
pi-chan/ViewControllers/Preview/PreviewViewController.swift
1
2775
// // PreviewViewController.swift // pi-chan // // Created by Kensuke Hoshikawa on 2016/04/12. // Copyright © 2016年 star__hoshi. All rights reserved. // import UIKit import SVProgressHUD import SafariServices import Cent class PreviewViewController: UIViewController, UIWebViewDelegate { var postNumber:Int! let localHtml = NSBundle.mainBundle().pathForResource("md", ofType: "html")! var post:Post? @IBOutlet weak var webView: UIWebView! @IBOutlet weak var rightBarButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() rightBarButton.setFAIcon(.FAEdit, iconSize: 22) let req = NSURLRequest(URL: NSURL(string: localHtml)!) webView.delegate = self; webView.loadRequest(req) } override func viewDidAppear(animated: Bool) { if Global.fromLogin || Global.posted { loadApi() Global.fromLogin = false Global.posted = false } } func loadApi(){ SVProgressHUD.showWithStatus("Loading...") Esa(token: KeychainManager.getToken()!, currentTeam: KeychainManager.getTeamName()!).post(postNumber){ result in SVProgressHUD.dismiss() switch result { case .Success(let post): self.post = post self.navigationItem.title = post.name let md = post.bodyMd.replaceNewLine() let js = "insert('\(md.stringByReplacingOccurrencesOfString("'",withString: "\\'"))');" log?.debug("\(js)") self.webView.stringByEvaluatingJavaScriptFromString(js) case .Failure(let error): ErrorHandler.errorAlert(error, controller: self) } } } func webViewDidFinishLoad(webView: UIWebView) { loadApi() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL!.absoluteString =~ "file:///posts" { goPreviewToPreview(request.URL!) return false } if navigationType == .Other{ return true }else{ let safari = SFSafariViewController(URL: request.URL!, entersReaderIfAvailable: true) presentViewController(safari, animated: true, completion: nil) return false } } func goPreviewToPreview(url:NSURL){ let nextPostNumber = Int(url.absoluteString.stringByReplacingOccurrencesOfString("file:///posts/",withString: ""))! performSegueWithIdentifier("PreviewToPreview", sender: nextPostNumber) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let previewViewController:PreviewViewController = segue.destinationViewController as! PreviewViewController previewViewController.postNumber = sender as! Int } @IBAction func openEditor(sender: AnyObject) { Window.openEditor(self, post: post) } }
mit
berrylux/waymark
Source/UIViewControllerExtensions.swift
1
1726
// // UIViewControllerExtensions.swift // // Copyright (c) 2016 Berrylux // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public extension UIViewController { public var top: UIViewController { if let navigationController = self as? UINavigationController { return navigationController.top } else if let tabBarController = self as? UITabBarController, selectedViewController = tabBarController.selectedViewController { return selectedViewController.top } else if let presentedViewController = presentedViewController { return presentedViewController.top } return self } }
mit
ymesika/Kitura-HTTP2
Sources/KituraHTTP2/HTTP2ConnectionUpgradeFactory.swift
1
2685
/* * Copyright IBM Corporation 2017 * * 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 KituraNet import LoggerAPI public class HTTP2ConnectionUpgradeFactory: ConnectionUpgradeFactory { /// The name of the protocol supported by this `ConnectionUpgradeFactory`. public let name = "h2c" /// Create an instance of this 'ConnectionUpgradeFactory' init() { ConnectionUpgrader.register(factory: self) } /// "Upgrade" a connection to the HTTP/2 protocol. /// /// - Parameter handler: The `IncomingSocketHandler` that is handling the connection being upgraded. /// - Parameter request: The `ServerRequest` object of the incoming "upgrade" request. /// - Parameter response: The `ServerResponse` object that will be used to send the response of the "upgrade" request. /// /// - Returns: A tuple of the created `IncomingSocketProcessor` and a message to send as the body of the response to /// the upgrade request. The `IncomingSocketProcessor` should be nil if the upgrade request wasn't successful. /// If the message is nil, the response will not contain a body. public func upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, String?) { guard let settings = request.headers["HTTP2-Settings"] else { return (nil, "Upgrade request MUST include exactly one 'HTTP2-Settings' header field.") } guard settings.count == 1 else { return (nil, "Upgrade request MUST include exactly one 'HTTP2-Settings' header field.") } guard let decodedSettings = Data(base64Encoded: HTTP2Utils.base64urlToBase64(base64url: settings[0])) else { return (nil, "Value for 'HTTP2-Settings' is not Base64 URL encoded") } response.statusCode = .switchingProtocols let session = HTTP2Session(settingsPayload: decodedSettings, with: request) let processor = HTTP2SocketProcessor(session: session, upgrade: true) session.processor = processor return (processor, nil) } }
apache-2.0
austinzheng/swift
validation-test/compiler_crashers_fixed/01782-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
65
492
// 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 class A<T) { let t: T { let h: start, ") } func x: String { enum A { func b((T.a) init() + se
apache-2.0
austinzheng/swift
validation-test/compiler_crashers_2_fixed/0184-8764.swift
34
353
// RUN: %target-swift-frontend -emit-ir %s @discardableResult public func applyWrapped<T, U>(function: Optional<(T) -> U>, to value: Optional<T>) -> Optional<U> { switch (function, value) { case (let .some(f), let .some(v)): return .some(f(v)) case (.none, _): return .none case (_, .none): return .none } }
apache-2.0
developerY/Swift2_Playgrounds
Swift2LangRef.playground/Pages/Advanced Operations.xcplaygroundpage/Contents.swift
1
10508
//: [Previous](@previous) //: ------------------------------------------------------------------------------------------------ //: Things to know: //: //: * Arithmetic operators in Swift do not automatically overflow. Adding two values that overflow //: their type (for example, storing 300 in a UInt8) will cause an error. There are special //: operators that allow overflow, including dividing by zero. //: //: * Swift allows developers to define their own operators, including those that Swift doesn't //: currently define. You can even specify the associativity and precedence for operators. //: ------------------------------------------------------------------------------------------------ //: ------------------------------------------------------------------------------------------------ //: Bitwise Operators //: //: The Bitwise operators (AND, OR, XOR, etc.) in Swift effeectively mirror the functionality that //: you're used to with C++ and Objective-C. //: //: We'll cover them briefly. The odd formatting is intended to help show the results: var andResult: UInt8 = 0b00101111 & 0b11110100 //: 0b00100100 <- result var notResult: UInt8 = ~0b11110000 //: 0b00001111 <- result var orResult: UInt8 = 0b01010101 | 0b11110000 //: 0b11110101 <- result var xorResult: UInt8 = 0b01010101 ^ 0b11110000 //: 0b10100101 <- result //: Shifting in Swift is slightly different than in C++. //: //: A lesser-known fact about C++ is that the signed right-shift of a signed value is //: implementation specific. Most compilers do what most programmers expect, which is an arithmetic //: shift (which maintains the sign bit and shifts 1's into the word from the right.) //: //: Swift defines this behavior to be what you expect, shifting signed values to the right will //: perform an arithmetic shift using two's compilment. var leftShiftUnsignedResult: UInt8 = 32 << 1 var leftShiftSignedResult: Int8 = 32 << 1 var leftShiftSignedNegativeResult: Int8 = -32 << 1 var rightShiftUnsignedResult: UInt8 = 32 >> 1 var rightShiftSignedResult: Int8 = 32 >> 1 var rightShiftSignedNegativeResult: Int8 = -32 >> 1 //: ------------------------------------------------------------------------------------------------ //: Overflow operators //: //: If an arithmetic operation (specifically addition (+), subtraction (-) and multiplication (*)) //: results in a value too large or too small for the constant or variable that the result is //: intended for, Swift will produce an overflow/underflow error. //: //: The last two lines of this code block will trigger an overflow/underflow: //: //: var positive: Int8 = 120 //: var negative: Int8 = -120 //: var overflow: Int8 = positive + positive //: var underflow: Int8 = negative + negative //: //: This is also true for division by zero, which can be caused with the division (/) or remainder //: (%) operators. //: //: Sometimes, however, overflow and underflow behavior is exactly what the programmer may intend, //: so Swift provides specific overflow/underflow operators which will not trigger an error and //: allow the overflow/underflow to perform as we see in C++/Objective-C. //: //: Special operators for division by zero are also provided, which return 0 in the case of a //: division by zero. //: //: Here they are, in all their glory: var someValue: Int8 = 120 var aZero: Int8 = someValue - someValue var overflowAdd: Int8 = someValue &+ someValue var underflowSub: Int8 = -someValue &- someValue var overflowMul: Int8 = someValue &* someValue // removed - var divByZero: Int8 = 100 &/ aZero // removed - var remainderDivByZero: Int8 = 100 &% aZero //: ------------------------------------------------------------------------------------------------ //: Operator Functions (a.k.a., Operator Overloading) //: //: Most C++ programmers should be familiar with the concept of operator overloading. Swift offers //: the same kind of functionality as well as additional functionality of specifying the operator //: precednce and associativity. //: //: The most common operators will usually take one of the following forms: //: //: * prefix: the operator appears before a single identifier as in "-a" or "++i" //: * postfix: the operator appears after a single identifier as in "i++" //: * infix: the operator appears between two identifiers as in "a + b" or "c / d" //: //: These are specified with the three attributes, @prefix, @postfix and @infix. //: //: There are more types of operators (which use different attributes, which we'll cover shortly. //: //: Let's define a Vector2D class to work with: struct Vector2D { var x = 0.0 var y = 0.0 } //: Next, we'll define a simple vector addition (adding the individual x & y components to create //: a new vector.) //: //: Since we're adding two Vector2D instances, we'll use operator "+". We want our addition to take //: the form "vectorA + vectorB", which means we'll be defining an infix operator. //: //: Here's what that looks like: func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } //: Let's verify our work: var a = Vector2D(x: 1.0, y: 2.0) var b = Vector2D(x: 3.0, y: 4.0) var c = a + b //: We've seen the infix operator at work so let's move on to the prefix and postfix operators. //: We'll define a prefix operator that negates the vector taking the form (result = -value): prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } //: Check our work: c = -a //: Next, let's consider the common prefix increment operator (++a) and postfix increment (a++) //: operations. Each of these performs the operation on a single value whle also returning the //: appropriate result (either the original value before the increment or the value after the //: increment.) //: //: Each will either use the @prefix or @postfix attribute, but since they also modify the value //: they are also @assigmnent operators (and make use of inout for the parameter.) //: //: Let's take a look: prefix func ++ (inout vector: Vector2D) -> Vector2D { vector = vector + Vector2D(x: 1.0, y: 1.0) return vector } postfix func ++ (inout vector: Vector2D) -> Vector2D { var previous = vector; vector = vector + Vector2D(x: 1.0, y: 1.0) return previous } //: And we can check our work: ++c c++ c //: Equivalence Operators allow us to define a means for checking if two values are the same //: or equivalent. They can be "equal to" (==) or "not equal to" (!=). These are simple infix //: opertors that return a Bool result. //: //: Let's also take a moment to make sure we do this right. When comparing floating point values //: you can either check for exact bit-wise equality (a == b) or you can compare values that are //: "very close" by using an epsilon. It's important to recognize the difference, as there are //: cases when IEEE floating point values should be equal, but are actually represented differently //: in their bit-wise format because they were calculated differently. In these cases, a simple //: equality comparison will not suffice. //: //: So here are our more robust equivalence operators: let Epsilon = 0.1e-7 func == (left: Vector2D, right: Vector2D) -> Bool { if abs(left.x - right.x) > Epsilon { return false } if abs(left.y - right.y) > Epsilon { return false } return true } func != (left: Vector2D, right: Vector2D) -> Bool { // Here, we'll use the inverted result of the "==" operator: return !(left == right) } //: ------------------------------------------------------------------------------------------------ //: Custom Operators //: //: So far, we've been defining operator functions for operators that Swift understands and //: for which Swift provides defined behaviors. We can also define our own custom operators for //: doing other interestig things. //: //: For example, Swift doesn't support the concept of a "vector normalization" or "cross product" //: because this functionality doesn't apply to any of the types Swift offers. //: //: Let's keep it simple, though. How about an operator that adds a vector to itself. Let's make //: this a prefix operator that takes the form "+++value" //: //: First, we we must introduce Swift to our new operator. The syntax takes the form of the //: 'operator' keyword, folowed by either 'prefix', 'postfix' or 'infix': //: //: Swift meet operator, operator meet swift: prefix operator +++ {} //: Now we can declare our new operator: prefix func +++ (inout vector: Vector2D) -> Vector2D { vector = vector + vector return vector } //: Let's check our work: var someVector = Vector2D(x: 5.0, y: 9.0) +++someVector //: ------------------------------------------------------------------------------------------------ //: Precedence and Associativity for Custom Infix Operators //: //: Custom infix operators can define their own associativity (left-to-right or right-to-left or //: none) as well as a precedence for determining the order of operations. //: //: Associativity values are 'left' or 'right' or 'none'. //: //: Precedence values are ranked with a numeric value. If not specified, the default value is 100. //: Operations are performed in order of precedence, with higher values being performed first. The //: precedence values are relative to all other precedence values for other operators. The following //: are the default values for operator precedence in the Swift standard library: //: //: 160 (none): Operators << >> //: 150 (left): Operators * / % &* &/ &% & //: 140 (left): Operators + - &+ &- | ^ //: 135 (none): Operators .. ... //: 132 (none): Operators is as //: 130 (none): Operators < <= > >= == != === !== ~= //: 120 (left): Operators && //: 110 (left): Operators || //: 100 (right): Operators ?: //: 90 (right): Operators = *= /= %= += -= <<= >>= &= ^= |= &&= ||= //: //: Let's take a look at how we define a new custom infix operator with left associativity and a //: precedence of 140. //: //: We'll define a function that adds the 'x' components of two vectors, but subtracts the 'y' //: components. We'll call this the "+-" operator: infix operator +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } //: Check our work. Let's setup a couple vectors that result in a value of (0, 0): var first = Vector2D(x: 5.0, y: 5.0) var second = Vector2D(x: -5.0, y: 5.0) first +- second //: [Next](@next)
mit
benlangmuir/swift
validation-test/compiler_crashers_fixed/25504-swift-constraints-constraintgraphnode-getadjacency.swift
65
442
// 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 func b{.T:class A{struct B{let v:A}}class A
apache-2.0
kylry/KTSpectrum
Sample-Project/KTSpectrum Sample Project/AppDelegate.swift
1
3065
/* Copyright (c) 2016 Kyle Ryan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
brentdax/swift
test/Sanitizers/tsan.swift
1
1450
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=thread -o %t_tsan-binary // RUN: %target-codesign %t_tsan-binary // RUN: not env %env-TSAN_OPTIONS="abort_on_error=0" %target-run %t_tsan-binary 2>&1 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: tsan_runtime // UNSUPPORTED: OS=tvos // FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs // don't support TSan. // UNSUPPORTED: remote_run // https://bugs.swift.org/browse/SR-6622 // XFAIL: linux #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) import Glibc #endif // Make sure we can handle swifterror and don't bail during the LLVM // threadsanitizer pass. enum MyError : Error { case A } public func foobar(_ x: Int) throws { if x == 0 { throw MyError.A } } public func call_foobar() { do { try foobar(1) } catch(_) { } } // Test ThreadSanitizer execution end-to-end. var threads: [pthread_t] = [] var racey_x: Int; for _ in 1...5 { #if os(macOS) || os(iOS) var t : pthread_t? #else var t : pthread_t = 0 #endif pthread_create(&t, nil, { _ in print("pthread ran") racey_x = 5; return nil }, nil) #if os(macOS) || os(iOS) threads.append(t!) #else threads.append(t) #endif } for t in threads { if t == nil { print("nil thread") continue } pthread_join(t, nil) } // CHECK: ThreadSanitizer: data race
apache-2.0
mxcl/PromiseKit
Sources/Error.swift
2
3480
import Foundation public enum PMKError: Error { /** The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`. This is invalid as per Cocoa/Apple calling conventions. */ case invalidCallingConvention /** A handler returned its own promise. 99% of the time, this is likely a programming error. It is also invalid per Promises/A+. */ case returnedSelf /** `when()`, `race()` etc. were called with invalid parameters, eg. an empty array. */ case badInput /// The operation was cancelled case cancelled /// `nil` was returned from `flatMap` @available(*, deprecated, message: "See: `compactMap`") case flatMap(Any, Any.Type) /// `nil` was returned from `compactMap` case compactMap(Any, Any.Type) /** The lastValue or firstValue of a sequence was requested but the sequence was empty. Also used if all values of this collection failed the test passed to `firstValue(where:)`. */ case emptySequence /// no winner in `race(fulfilled:)` case noWinner } extension PMKError: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .flatMap(let obj, let type): return "Could not `flatMap<\(type)>`: \(obj)" case .compactMap(let obj, let type): return "Could not `compactMap<\(type)>`: \(obj)" case .invalidCallingConvention: return "A closure was called with an invalid calling convention, probably (nil, nil)" case .returnedSelf: return "A promise handler returned itself" case .badInput: return "Bad input was provided to a PromiseKit function" case .cancelled: return "The asynchronous sequence was cancelled" case .emptySequence: return "The first or last element was requested for an empty sequence" case .noWinner: return "All thenables passed to race(fulfilled:) were rejected" } } } extension PMKError: LocalizedError { public var errorDescription: String? { return debugDescription } } //////////////////////////////////////////////////////////// Cancellation /// An error that may represent the cancelled condition public protocol CancellableError: Error { /// returns true if this Error represents a cancelled condition var isCancelled: Bool { get } } extension Error { public var isCancelled: Bool { do { throw self } catch PMKError.cancelled { return true } catch let error as CancellableError { return error.isCancelled } catch URLError.cancelled { return true } catch CocoaError.userCancelled { return true } catch let error as NSError { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let domain = error.domain let code = error.code return ("SKErrorDomain", 2) == (domain, code) #else return false #endif } catch { return false } } } /// Used by `catch` and `recover` public enum CatchPolicy { /// Indicates that `catch` or `recover` handle all error types including cancellable-errors. case allErrors /// Indicates that `catch` or `recover` handle all error except cancellable-errors. case allErrorsExceptCancellation }
mit
Vanlol/MyYDW
SwiftCocoaUITests/SwiftCocoaUITests.swift
1
1246
// // SwiftCocoaUITests.swift // SwiftCocoaUITests // // Created by admin on 2017/6/20. // Copyright © 2017年 admin. All rights reserved. // import XCTest class SwiftCocoaUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/TextField/TextFieldType.swift
1
13159
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import Localization import ToolKit /// The type of the text field public enum TextFieldType: Hashable { /// Address line case addressLine(Int) /// City case city /// State (country) case state /// Post code case postcode /// Person full name case personFullName /// Cardholder name case cardholderName /// Expiry date formatted as MMyy case expirationDate /// CVV case cardCVV /// Credit card number case cardNumber /// Email field case email /// New password field. Sometimes appears alongside `.confirmNewPassword` case newPassword /// New password confirmation field. Always alongside `.newPassword` case confirmNewPassword /// Password for auth case password /// Current password for changing to new password case currentPassword /// A single word from the mnemonic used for backup verification. /// The index is the index of the word in the mnemonic. case backupVerification(index: Int) /// Mobile phone number entry case mobile /// One time code entry case oneTimeCode /// A description of a event case description /// A memo of a transaction. case memo /// A crypto address type case cryptoAddress } // MARK: - Debug extension TextFieldType: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .memo: return "memo" case .description: return "description" case .email: return "email" case .newPassword: return "new-password" case .confirmNewPassword: return "confirm-new-password" case .password: return "password" case .currentPassword: return "current-password" case .backupVerification(let index): return "backup-verification-\(index)" case .mobile: return "mobile-number" case .oneTimeCode: return "one-time-code" case .cardholderName: return "cardholder-name" case .expirationDate: return "expiry-date" case .cardCVV: return "card-cvv" case .cardNumber: return "card-number" case .addressLine: return "address-line" case .city: return "city" case .state: return "state" case .postcode: return "post-code" case .personFullName: return "person-full-name" case .cryptoAddress: return "crypto-address" } } } // MARK: - Information Sensitivity extension TextFieldType { /// Whether the text field should cleanup on backgrounding var requiresCleanupOnBackgroundState: Bool { switch self { case .password, .currentPassword, .newPassword, .confirmNewPassword, .backupVerification, .oneTimeCode, .cardNumber, .cardCVV: return true case .email, .mobile, .personFullName, .city, .state, .addressLine, .postcode, .cardholderName, .description, .expirationDate, .cryptoAddress, .memo: return false } } } // MARK: - Accessibility extension TextFieldType { /// Provides accessibility attributes for the `TextFieldView` var accessibility: Accessibility { typealias AccessibilityId = Accessibility.Identifier.TextFieldView switch self { case .description: return .id(AccessibilityId.description) case .cardNumber: return .id(AccessibilityId.Card.number) case .cardCVV: return .id(AccessibilityId.Card.cvv) case .expirationDate: return .id(AccessibilityId.Card.expirationDate) case .cardholderName: return .id(AccessibilityId.Card.name) case .email: return .id(AccessibilityId.email) case .newPassword: return .id(AccessibilityId.newPassword) case .confirmNewPassword: return .id(AccessibilityId.confirmNewPassword) case .password: return .id(AccessibilityId.password) case .currentPassword: return .id(AccessibilityId.currentPassword) case .mobile: return .id(AccessibilityId.mobileVerification) case .oneTimeCode: return .id(AccessibilityId.oneTimeCode) case .backupVerification: return .id(AccessibilityId.backupVerification) case .addressLine(let number): return .id("\(AccessibilityId.addressLine)-\(number)") case .personFullName: return .id(AccessibilityId.personFullName) case .city: return .id(AccessibilityId.city) case .state: return .id(AccessibilityId.state) case .postcode: return .id(AccessibilityId.postCode) case .cryptoAddress: return .id(AccessibilityId.cryptoAddress) case .memo: return .id(AccessibilityId.memo) } } /// This is `true` if the text field should show hints during typing var showsHintWhileTyping: Bool { switch self { case .email, .backupVerification, .addressLine, .city, .postcode, .personFullName, .state, .mobile, .cardCVV, .expirationDate, .cardholderName, .description, .cardNumber, .memo: return false case .password, .currentPassword, .newPassword, .confirmNewPassword, .oneTimeCode, .cryptoAddress: return true } } /// The title of the text field var placeholder: String { typealias LocalizedString = LocalizationConstants.TextField.Placeholder switch self { case .cardCVV: return LocalizedString.cvv case .expirationDate: return LocalizedString.expirationDate case .oneTimeCode: return LocalizedString.oneTimeCode case .description: return LocalizedString.noDescription case .memo: return LocalizedString.noMemo case .cryptoAddress: return LocalizedString.addressOrDomain case .password, .currentPassword, .newPassword, .confirmNewPassword, .email, .backupVerification, .addressLine, .city, .postcode, .personFullName, .state, .mobile, .cardholderName, .cardNumber: return "" } } /// The title of the text field var title: String { typealias LocalizedString = LocalizationConstants.TextField.Title switch self { case .description: return LocalizedString.description case .cardholderName: return LocalizedString.Card.name case .expirationDate: return LocalizedString.Card.expirationDate case .cardNumber: return LocalizedString.Card.number case .cardCVV: return LocalizedString.Card.cvv case .email: return LocalizedString.email case .password: return LocalizedString.password case .currentPassword: return LocalizedString.currentPassword case .newPassword: return LocalizedString.newPassword case .confirmNewPassword: return LocalizedString.confirmNewPassword case .mobile: return LocalizedString.mobile case .oneTimeCode: return LocalizedString.oneTimeCode case .backupVerification(index: let index): return index.placeholder case .addressLine(let number): return "\(LocalizedString.addressLine) \(number)" case .city: return LocalizedString.city case .state: return LocalizedString.state case .postcode: return LocalizedString.postCode case .personFullName: return LocalizedString.fullName case .cryptoAddress: return "" case .memo: return LocalizedString.memo } } // `UIKeyboardType` of the textField var keyboardType: UIKeyboardType { switch self { case .email: return .emailAddress case .newPassword, .confirmNewPassword, .password, .currentPassword, .backupVerification, .oneTimeCode, .description, .cryptoAddress, .memo: return .default case .mobile: return .phonePad case .expirationDate, .cardCVV, .cardNumber: return .numberPad case .addressLine, .cardholderName, .personFullName, .city, .state, .postcode: return .asciiCapable } } var autocapitalizationType: UITextAutocapitalizationType { switch self { case .oneTimeCode: return .allCharacters case .cardholderName, .city, .state, .personFullName, .addressLine: return .words case .backupVerification, .password, .currentPassword, .newPassword, .confirmNewPassword, .email, .mobile, .cardCVV, .expirationDate, .cardNumber, .postcode, .description, .cryptoAddress, .memo: return .none } } /// Returns `true` if the text-field's input has to be secure var isSecure: Bool { switch self { case .email, .backupVerification, .cardCVV, .cardholderName, .expirationDate, .cardNumber, .mobile, .oneTimeCode, .addressLine, .city, .state, .postcode, .personFullName, .description, .cryptoAddress, .memo: return false case .newPassword, .confirmNewPassword, .password, .currentPassword: return true } } /// Returns `UITextAutocorrectionType` var autocorrectionType: UITextAutocorrectionType { .no } /// The `UITextContentType` of the textField which can /// drive auto-fill behavior. var contentType: UITextContentType? { switch self { case .mobile: return .telephoneNumber case .cardNumber: return .creditCardNumber case .cardholderName: return .name case .expirationDate, .cardCVV, .backupVerification, .description, .cryptoAddress, .memo: return nil case .email: return .emailAddress case .oneTimeCode: return .oneTimeCode case .newPassword, .confirmNewPassword: return .newPassword case .password, .currentPassword: /// Disable password suggestions (avoid setting `.password` as value) return UITextContentType(rawValue: "") case .addressLine(let line): switch line { case 1: // Line 1 return .streetAddressLine1 default: // 2 return .streetAddressLine2 } case .city: return .addressCity case .state: return .addressState case .postcode: return .postalCode case .personFullName: return .name } } } extension Int { fileprivate typealias Index = LocalizationConstants.VerifyBackupScreen.Index fileprivate var placeholder: String { switch self { case 0: return Index.first case 1: return Index.second case 2: return Index.third case 3: return Index.fourth case 4: return Index.fifth case 5: return Index.sixth case 6: return Index.seventh case 7: return Index.eighth case 8: return Index.ninth case 9: return Index.tenth case 10: return Index.eleventh case 11: return Index.twelfth default: return "" } } }
lgpl-3.0