repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wess/Appendix
refs/heads/master
Sources/ios/UIView+Appendix.swift
mit
1
// // UIView+Appendix.swift // Appendix // // Created by Wesley Cope on 6/29/15. // Copyright (c) 2015 Wess Cope. All rights reserved. // import Foundation import UIKit import QuartzCore func RadiansFromDegrees(degrees:Float) -> Float { return degrees * Float(M_PI) / 180 } public enum UIViewCorner { case topLeft case topRight case bottomLeft case bottomRight public static let all:[UIViewCorner] = [.topLeft, .topRight, .bottomLeft, .bottomRight] var mask:CACornerMask { switch self { case .topLeft: return CACornerMask.layerMinXMinYCorner case .topRight: return CACornerMask.layerMinXMaxYCorner case .bottomLeft: return CACornerMask.layerMaxXMinYCorner case .bottomRight: return CACornerMask.layerMaxXMinYCorner } } } @available(iOS 11.0, *) public extension UIView { /// Shortcut to the frame's origin. public var origin:CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } /// Shortcut to the frame's size. public var size:CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } /// Shortcut to the frame's width. public var width:CGFloat { get { return self.frame.width } set { var size = self.size size.width = newValue var frame = self.frame frame.size = size self.frame = frame } } /// Shortcut to the frame's height. public var height:CGFloat { get { return self.frame.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } /// Shortcut to the frame's top. public var top:CGFloat { get { return self.frame.top } set { var origin = self.origin origin.y = newValue var frame = self.frame frame.origin = origin self.frame = frame } } /// Shortcut to the frame's right. public var right:CGFloat { get { return left + width } set { var origin = self.origin origin.x = newValue - self.width var frame = self.frame frame.origin = origin self.frame = frame } } /// Shortcut to the frame's bottom. public var bottom:CGFloat { get { return top + height } set { var origin = self.origin origin.y = newValue - self.height var frame = self.frame frame.origin = origin self.frame = frame } } /// Shortcut to the frame's left. public var left:CGFloat { get { return self.frame.minX } set { var origin = self.origin origin.x = newValue var frame = self.frame frame.origin = origin self.frame = frame } } /// Shortcut to the layer's corner radius. public var cornerRadius:CGFloat { get { return self.layer.cornerRadius } set { self.clipsToBounds = newValue > 0 self.layer.cornerRadius = newValue } } public var roundedCorners:[UIViewCorner] { get { var corners:[UIViewCorner] = [] if layer.maskedCorners.contains(.layerMinXMinYCorner) { corners.append(.topLeft) } if layer.maskedCorners.contains(.layerMaxXMinYCorner) { corners.append(.topRight) } if layer.maskedCorners.contains(.layerMinXMaxYCorner) { corners.append(.bottomLeft) } if layer.maskedCorners.contains(.layerMaxXMaxYCorner) { corners.append(.bottomRight) } return corners } set { layer.maskedCorners = newValue.reduce(CACornerMask()) { CACornerMask(rawValue: $0.rawValue << $1.mask.rawValue) } } } /// Shortcut to the layer's border width. public var borderWidth:CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } /// Shortcut to the layer's border color. public var borderColor:UIColor { get { return UIColor(cgColor: self.layer.borderColor!) } set { self.layer.borderColor = (newValue as UIColor).cgColor } } /// Shortcut to the layer's shadow opacity. public var shadowOpacity:CGFloat { get { return CGFloat(self.layer.shadowOpacity) } set { self.layer.shadowOpacity = Float(newValue) } } /// Shortcut to the layer's shadow color. public var shadowColor:UIColor? { get { return self.layer.shadowColor == nil ? UIColor(cgColor: self.layer.shadowColor!) : nil } set { self.layer.shadowColor = newValue == nil ? nil : newValue!.cgColor } } /// Shortcut to the layer's shadow offset. public var shadowOffset:CGSize { get { return self.layer.shadowOffset } set { self.layer.shadowOffset = newValue } } /// Shortcut to the layer's shadow radius. public var shadowRadius:CGFloat { get { return self.layer.shadowRadius } set { self.layer.shadowRadius = newValue } } /// Shortcut to the layer's shadow path. public var shadowPath:CGPath? { get { return self.layer.shadowPath } set { self.layer.shadowPath = newValue } } /// UIImage representation of the view. public var snapshot:UIImage { get { UIGraphicsBeginImageContextWithOptions(size, true, 0) drawHierarchy(in: bounds, afterScreenUpdates: true) let rasterizedView = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return rasterizedView! } } /// Set to make view background gradient. public var gradientBackgroundColors:[UIColor] { get { return [] } set { let gradLayer = CAGradientLayer() gradLayer.colors = newValue.map { $0.cgColor } gradLayer.frame = bounds layer.addSublayer(gradLayer) } } /** Animate the rotation of the view. - parameter degrees: Amount to rotate the view by. - parameter duration: How long animation will run. - parameter completion: Block called when the animation is complete. */ public func rotate(degrees:Float, duration:TimeInterval, completion:@escaping ((Bool) -> Void)) { UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in self.transform = self.transform.rotated(by: CGFloat(RadiansFromDegrees(degrees: degrees))) }, completion: completion) } /** Animate the scaling of the view. - parameter offset: Amount to scale the view by. - parameter duration: How long animation will run. - parameter completion: Block called when the animation is complete. */ public func scale(offset:CGPoint, duration:TimeInterval, completion:@escaping ((Bool) -> Void)) { UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in self.transform = self.transform.scaledBy(x: offset.x, y: offset.y) }, completion: completion) } /** Add multiple views, as subviews. - parameter subviews: Array of views to add. - returns: Current view instance. */ @discardableResult public func addSubviews(_ subviews:[UIView]) -> UIView { subviews.forEach(addSubview) return self } /** Add multiple views, as subviews. - parameter args: Comma separated list of views (as arguments) to add. - returns: Current view instance. */ @discardableResult public func addSubviews(_ args:UIView...) -> UIView { args.forEach(addSubview) return self } /** Adds view instance, as a subview, to another view. - parameter to: View to add view instance to - returns: Current view instance. */ @discardableResult public func add(to: UIView) -> UIView { to.addSubview(self) return self } /** Cycles layout, forcing call to `layout`. - returns: Current view instance. */ @discardableResult public func cycleLayout() -> UIView { self.setNeedsLayout() self.layoutIfNeeded() return self } /** Cycles constraints, forcing call to `updateConstraints`. - returns: Current view instance. */ @discardableResult public func cycleConstraints() -> UIView { self.setNeedsUpdateConstraints() self.updateConstraintsIfNeeded() return self } } fileprivate struct UIViewAnimationDefaults { static let Duration:TimeInterval = 1 static let Damping:CGFloat = 0.5 static let Velocity:CGFloat = 0.5 } extension UIView /* Animations */ { /** Animates shaking with view (left and right). - parameter times: Number of times view should shake. - returns: Current view instance. */ @discardableResult public func shake(_ times:Int) -> UIView { let keyframe = CAKeyframeAnimation(keyPath: "transform") keyframe.autoreverses = true keyframe.repeatCount = Float(times) keyframe.duration = 7/100 keyframe.values = [ NSValue(caTransform3D: CATransform3DMakeTranslation(-5, 0, 0 )), NSValue(caTransform3D: CATransform3DMakeTranslation( 5, 0, 0 )) ] self.layer.add(keyframe, forKey: nil) return self } /** Animates springing with view. - parameter animations: Block used for changing properties of the view during animation. - parameter completion: Block called when the animation is complete. - returns: Current view instance. */ @discardableResult public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) -> UIView { return spring(duration: UIViewAnimationDefaults.Duration, animations: animations, completion: completion) } /** Animates springing with view. - parameter duration: How long animation will run. - parameter animations: Block used for changing properties of the view during animation. - parameter completion: Block called when the animation is complete. - returns: Current view instance. */ @discardableResult public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) -> UIView { UIView.animate( withDuration: UIViewAnimationDefaults.Duration, delay: 0, usingSpringWithDamping: UIViewAnimationDefaults.Damping, initialSpringVelocity: UIViewAnimationDefaults.Velocity, options: UIView.AnimationOptions.allowAnimatedContent, animations: animations, completion: completion ) return self } }
e8518140a3a998db4f94c37e7b9e56d9
22.613391
129
0.626635
false
false
false
false
jpedrosa/sua
refs/heads/master
Sources/byte_stream.swift
apache-2.0
1
public typealias FirstCharTable = [[[UInt8]]?] public let FirstCharTableValue = [[UInt8]]() public struct ByteStream { public var _bytes: [UInt8] = [] public var startIndex = 0 public var currentIndex = 0 public var lineEndIndex = 0 public var milestoneIndex = 0 public init(bytes: [UInt8] = [], startIndex: Int = 0, lineEndIndex: Int = 0) { self.startIndex = startIndex self.lineEndIndex = lineEndIndex _bytes = bytes currentIndex = startIndex if lineEndIndex == 0 { self.lineEndIndex = bytes.count } } public var bytes: [UInt8] { get { return _bytes } set { _bytes = newValue currentIndex = 0 startIndex = 0 lineEndIndex = newValue.count } } public mutating func reset() { currentIndex = 0 startIndex = 0 lineEndIndex = _bytes.count } public var isEol: Bool { return currentIndex >= lineEndIndex } public var current: UInt8 { return _bytes[currentIndex] } public func peek() -> UInt8? { return currentIndex < lineEndIndex ? _bytes[currentIndex] : nil } public mutating func next() -> UInt8? { var r: UInt8? if currentIndex < lineEndIndex { r = _bytes[currentIndex] currentIndex += 1 } return r } public mutating func eat(fn: (c: UInt8) -> Bool) -> Bool { return match(consume: true, fn: fn) } public mutating func match(consume: Bool = false, fn: (c: UInt8) -> Bool) -> Bool { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if fn(c: c) { if consume { currentIndex = i + 1 } return true } } return false } public mutating func eatOne(c: UInt8) -> Bool { return matchOne(c: c, consume: true) } public mutating func matchOne(c: UInt8, consume: Bool = false) -> Bool { let i = currentIndex if i < lineEndIndex && c == _bytes[i] { if consume { currentIndex = i + 1 } return true } return false } public mutating func eatWhileOne(c: UInt8) -> Bool { return matchWhileOne(c: c, consume: true) >= 0 } public mutating func matchWhileOne(c: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { if c != _bytes[i] { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatSpace() -> Bool { return matchSpace(consume: true) >= 0 } public mutating func eatWhileSpace() -> Bool { return matchWhileSpace(consume: true) >= 0 } public mutating func matchSpace(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if c == 32 || c == 160 { // space or \u00a0 if consume { currentIndex = i + 1 } return c } } return nil } public mutating func matchWhileSpace(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if c != 32 && c != 160 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatSpaceTab() -> Bool { return matchSpaceTab(consume: true) != nil } public mutating func eatWhileSpaceTab() -> Bool { return matchWhileSpaceTab(consume: true) >= 0 } public mutating func matchSpaceTab(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if c == 32 || c == 160 || c == 9 { // space or \u00a0 or tab if consume { currentIndex = i + 1 } return c } } return nil } public mutating func matchWhileSpaceTab(consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c != 32 && c != 160 && c != 9 { // space or \u00a0 or tab break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func skipToEnd() -> Bool { currentIndex = lineEndIndex return true } public func findIndex(c: UInt8, startAt: Int = 0) -> Int { let len = _bytes.count let lim = len - 2 var i = startAt while i < lim { if _bytes[i] == c || _bytes[i + 1] == c || _bytes[i + 2] == c { break } i += 3 } while i < len { if _bytes[i] == c { return i } i += 1 } return -1 } public mutating func skipTo(c: UInt8) -> Int { let r = findIndex(c: c, startAt: currentIndex) if r >= startIndex && r < lineEndIndex { currentIndex = r } return r } public mutating func backUp(n: Int) { currentIndex -= n } public mutating func keepMilestoneIfNot(fn: () -> Bool) -> Bool { let r = fn() if !r { milestoneIndex = currentIndex + 1 } return r } public mutating func yankMilestoneIfNot(fn: () -> Bool) -> Bool { if !fn() { milestoneIndex = currentIndex + 1 } return false } public mutating func eatUntil(fn: (c: UInt8) -> Bool) -> Bool { return matchUntil(consume: true, fn: fn) >= 0 } public mutating func matchUntil(consume: Bool = false, fn: (c: UInt8) -> Bool) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { if fn(c: _bytes[i]) { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhile(fn: (c: UInt8) -> Bool) -> Bool { return matchWhile(consume: true, fn: fn) >= 0 } public mutating func matchWhile(consume: Bool = false, fn: (c: UInt8) -> Bool) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { if !fn(c: _bytes[i]) { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func seekContext(fn: (c: UInt8) -> Bool) -> Bool { return matchContext(consume: true, fn: fn) >= 0 } public mutating func matchContext(consume: Bool = false, fn: (c: UInt8) -> Bool) -> Int { var i = currentIndex let len = lineEndIndex while i < len { if fn(c: _bytes[i]) { if consume { currentIndex = i startIndex = i } return i } i += 1 } return -1 } public mutating func maybeEat(fn: (inout ctx: ByteStream) -> Bool) -> Bool { return maybeMatch(fn: fn) >= 0 } public mutating func maybeMatch(fn: (inout ctx: ByteStream) -> Bool) -> Int { let savei = currentIndex if fn(ctx: &self) { return currentIndex - savei } else if milestoneIndex > 0 { currentIndex = milestoneIndex milestoneIndex = 0 } else { currentIndex = savei } return -1 } public mutating func nestMatch(fn: (ctx: ByteStream) -> Bool) -> Int { var ctx = ByteStream._cloneFromPool(po: self) let savei = currentIndex if fn(ctx: ctx) { currentIndex = ctx.currentIndex return currentIndex - savei } else if ctx.milestoneIndex > 0 { currentIndex = ctx.milestoneIndex ctx.milestoneIndex = 0 } ByteStream._returnToPool(o: ctx) return -1 } public mutating func collectTokenString() -> String? { let s = currentTokenString startIndex = currentIndex return s } public mutating func collectToken() -> [UInt8] { let s = currentToken startIndex = currentIndex return s } static var _pool: [ByteStream] = [] static func _returnToPool(o: ByteStream) { _pool.append(o) } static func _cloneFromPool(po: ByteStream) -> ByteStream { if _pool.count > 0 { var o = _pool.removeLast() o._bytes = po._bytes // Could clone it too. o.startIndex = po.startIndex o.lineEndIndex = po.lineEndIndex o.currentIndex = po.currentIndex return o } else { var o = ByteStream(bytes: po._bytes, startIndex: po.startIndex, lineEndIndex: po.lineEndIndex) o.currentIndex = po.currentIndex return o } } public func clone() -> ByteStream { var o = ByteStream(bytes: _bytes, startIndex: startIndex, lineEndIndex: lineEndIndex) o.currentIndex = currentIndex return o } public mutating func eatString(string: String) -> Bool { return matchBytes(bytes: string.bytes, consume: true) >= 0 } public mutating func matchString(string: String, consume: Bool = false) -> Int { return matchBytes(bytes: string.bytes, consume: consume) } public mutating func eatBytes(bytes: [UInt8]) -> Bool { return matchBytes(bytes: bytes, consume: true) >= 0 } public mutating func matchBytes(bytes: [UInt8], consume: Bool = false) -> Int { let i = currentIndex let blen = bytes.count if i + blen - 1 < lineEndIndex && _bytes[i] == bytes[0] { for bi in 1..<blen { if _bytes[i + bi] != bytes[bi] { return -1 } } if consume { currentIndex += blen } return blen } return -1 } public mutating func eatOnEitherString(string1: String, string2: String) -> Bool { return matchOnEitherBytes(bytes1: string1.bytes, bytes2: string2.bytes, consume: true) >= 0 } // Used for case insensitive matching. public mutating func matchOnEitherString(string1: String, string2: String, consume: Bool = false) -> Int { return matchOnEitherBytes(bytes1: string1.bytes, bytes2: string2.bytes) } public mutating func eatOnEitherBytes(bytes1: [UInt8], bytes2: [UInt8]) -> Bool { return matchOnEitherBytes(bytes1: bytes1, bytes2: bytes2, consume: true) >= 0 } // Used for case insensitive matching. public mutating func matchOnEitherBytes(bytes1: [UInt8], bytes2: [UInt8], consume: Bool = false) -> Int { let blen = bytes1.count let i = currentIndex if i + blen - 1 < lineEndIndex { for bi in 0..<blen { let c = _bytes[i + bi] if c != bytes1[bi] && c != bytes2[bi] { return -1 } } if consume { currentIndex += blen } return blen } return -1 } public mutating func eatUntilString(string: String) -> Bool { return matchUntilBytes(bytes: string.bytes, consume: true) >= 0 } public mutating func matchUntilString(string: String, consume: Bool = false) -> Int { return matchUntilBytes(bytes: string.bytes, consume: consume) } public mutating func eatUntilBytes(bytes: [UInt8]) -> Bool { return matchUntilBytes(bytes: bytes, consume: true) >= 0 } public mutating func matchUntilBytes(bytes: [UInt8], consume: Bool = false) -> Int { var i = currentIndex let savei = i let blen = bytes.count let len = lineEndIndex - blen + 1 let fc = bytes[0] AGAIN: while i < len { if _bytes[i] == fc { for bi in 1..<blen { if _bytes[i + bi] != bytes[bi] { i += 1 continue AGAIN } } if consume { currentIndex = i } return i - savei } i += 1 } return -1 } // Triple quotes sequence public mutating func eatUntilThree(c1: UInt8, c2: UInt8, c3: UInt8) -> Bool { return matchUntilThree(c1: c1, c2: c2, c3: c3, consume: true) >= 0 } public mutating func matchUntilThree(c1: UInt8, c2: UInt8, c3: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex - 2 while i < len { if _bytes[i] == c1 && _bytes[i + 1] == c2 && _bytes[i + 2] == c3 { break } i += 1 } if i >= len { i = lineEndIndex } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatTwo(c1: UInt8, c2: UInt8) -> Bool { return matchTwo(c1: c1, c2: c2, consume: true) } public mutating func matchTwo(c1: UInt8, c2: UInt8, consume: Bool = false) -> Bool { let i = currentIndex if i < lineEndIndex - 1 && _bytes[i] == c1 && _bytes[i + 1] == c2 { if consume { currentIndex = i + 2 } return true } return false } public mutating func eatThree(c1: UInt8, c2: UInt8, c3: UInt8) -> Bool { return matchThree(c1: c1, c2: c2, c3: c3, consume: true) } public mutating func matchThree(c1: UInt8, c2: UInt8, c3: UInt8, consume: Bool = false) -> Bool { let i = currentIndex if i < lineEndIndex - 2 && _bytes[i] == c1 && _bytes[i + 1] == c2 && _bytes[i + 2] == c3 { if consume { currentIndex = i + 3 } return true } return false } public mutating func eatUntilOne(c: UInt8) -> Bool { return matchUntilOne(c: c, consume: true) >= 0 } public mutating func matchUntilOne(c: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { if _bytes[i] == c { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherTwo(c1: UInt8, c2: UInt8) -> Bool { return matchWhileNeitherTwo(c1: c1, c2: c2, consume: true) >= 0 } public mutating func matchWhileNeitherTwo(c1: UInt8, c2: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherThree(c1: UInt8, c2: UInt8, c3: UInt8) -> Bool { return matchWhileNeitherThree(c1: c1, c2: c2, c3: c3, consume: true) >= 0 } public mutating func matchWhileNeitherThree(c1: UInt8, c2: UInt8, c3: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 || c == c3 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherFour(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8) -> Bool { return matchWhileNeitherFour(c1: c1, c2: c2, c3: c3, c4: c4, consume: true) >= 0 } public mutating func matchWhileNeitherFour(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 || c == c3 || c == c4 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherFive(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8) -> Bool { return matchWhileNeitherFive(c1: c1, c2: c2, c3: c3, c4: c4, c5: c5, consume: true) >= 0 } public mutating func matchWhileNeitherFive(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 || c == c3 || c == c4 || c == c5 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherSix(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8, c6: UInt8) -> Bool { return matchWhileNeitherSix(c1: c1, c2: c2, c3: c3, c4: c4, c5: c5, c6: c6, consume: true) >= 0 } public mutating func matchWhileNeitherSix(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8, c6: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 || c == c3 || c == c4 || c == c5 || c == c6 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatWhileNeitherSeven(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8, c6: UInt8, c7: UInt8) -> Bool { return matchWhileNeitherSeven(c1: c1, c2: c2, c3: c3, c4: c4, c5: c5, c6: c6, c7: c7, consume: true) >= 0 } public mutating func matchWhileNeitherSeven(c1: UInt8, c2: UInt8, c3: UInt8, c4: UInt8, c5: UInt8, c6: UInt8, c7: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c == c1 || c == c2 || c == c3 || c == c4 || c == c5 || c == c6 || c == c7 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public var currentToken: [UInt8] { return [UInt8](_bytes[startIndex..<currentIndex]) } public var currentTokenString: String? { let ei = currentIndex - 1 return ei < startIndex ? nil : String.fromCharCodes(charCodes: _bytes, start: startIndex, end: ei) } // More specialization public mutating func eatDigit() -> Bool { return matchDigit(consume: true) != nil } public mutating func matchDigit(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if c >= 48 && c <= 57 { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileDigit() -> Bool { return matchWhileDigit(consume: true) >= 0 } public mutating func matchWhileDigit(consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if c < 48 || c > 57 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatLowerCase() -> Bool { return matchLowerCase(consume: true) != nil } // a-z public mutating func matchLowerCase(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if c >= 97 && c <= 122 { // a-z if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileLowerCase() -> Bool { return matchWhileLowerCase(consume: true) >= 0 } public mutating func matchWhileLowerCase(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if c < 97 || c > 122 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatUpperCase() -> Bool { return matchUpperCase(consume: true) != nil } // A-Z public mutating func matchUpperCase(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if c >= 65 && c <= 90 { // A-Z if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileUpperCase() -> Bool { return matchWhileUpperCase(consume: true) >= 0 } public mutating func matchWhileUpperCase(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if c < 65 || c > 90 { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatAlpha() -> Bool { return matchAlpha(consume: true) != nil } // A-Z a-z public mutating func matchAlpha(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) { // A-Z a-z if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileAlpha() -> Bool { return matchWhileAlpha(consume: true) >= 0; } public mutating func matchWhileAlpha(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatAlphaUnderline() -> Bool { return matchAlphaUnderline(consume: true) >= 0 } // A-Z a-z _ public mutating func matchAlphaUnderline(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] // A-Z a-z _ if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileAlphaUnderline() -> Bool { return matchWhileAlphaUnderline(consume: true) >= 0 } public mutating func matchWhileAlphaUnderline(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatAlphaUnderlineDigit() -> Bool { return matchAlphaUnderlineDigit(consume: true) != nil } // A-Z a-z _ 0-9 public mutating func matchAlphaUnderlineDigit(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] // A-Z a-z _ 0-9 if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || (c >= 48 && c <= 57) { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileAlphaUnderlineDigit() -> Bool { return matchWhileAlphaUnderlineDigit(consume: true) >= 0 } public mutating func matchWhileAlphaUnderlineDigit(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || (c >= 48 && c <= 57) { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatAlphaUnderlineDigitMinus() -> Bool { return matchAlphaUnderlineDigitMinus(consume: true) != nil } // A-Z a-z _ 0-9 public mutating func matchAlphaUnderlineDigitMinus(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] // A-Z a-z _ 0-9 - if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || (c >= 48 && c <= 57) || c == 45 { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileAlphaUnderlineDigitMinus() -> Bool { return matchWhileAlphaUnderlineDigitMinus(consume: true) >= 0 } public mutating func matchWhileAlphaUnderlineDigitMinus(consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex while i < len { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || (c >= 48 && c <= 57) || c == 45 { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatAlphaDigit() -> Bool { return matchAlphaDigit(consume: true) != nil } // A-Z a-z 0-9 public mutating func matchAlphaDigit(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] // A-Z a-z 0-9 if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileAlphaDigit() -> Bool { return matchWhileAlphaDigit(consume: true) >= 0 } public mutating func matchWhileAlphaDigit(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatHexa() -> Bool { return matchHexa(consume: true) != nil } // A-F a-f 0-9 public mutating func matchHexa(consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] // A-F a-f 0-9 if (c >= 65 && c <= 70) || (c >= 97 && c <= 102) || (c >= 48 && c <= 57) { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatWhileHexa() -> Bool { return matchWhileHexa(consume: true) >= 0 } public mutating func matchWhileHexa(consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if (c >= 65 && c <= 70) || (c >= 97 && c <= 102) || (c >= 48 && c <= 57) { // ignore } else { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } // One-off symbols public mutating func eatOpenParen() -> Bool { return matchOpenParen(consume: true) } // ( public mutating func matchOpenParen(consume: Bool = false) -> Bool { return matchOne(c: 40, consume: consume) // ( } public mutating func eatCloseParen() -> Bool { return matchCloseParen(consume: true) } // ) public mutating func matchCloseParen(consume: Bool = false) -> Bool { return matchOne(c: 41, consume: consume) // ) } public mutating func eatLessThan() -> Bool { return matchLessThan(consume: true) } // < public mutating func matchLessThan(consume: Bool = false) -> Bool { return matchOne(c: 60, consume: consume) // < } public mutating func eatGreaterThan() -> Bool { return matchGreaterThan(consume: true) } // > public mutating func matchGreaterThan(consume: Bool = false) -> Bool { return matchOne(c: 62, consume: consume) // > } public mutating func eatOpenBracket() -> Bool { return matchOpenBracket(consume: true) } // [ public mutating func matchOpenBracket(consume: Bool = false) -> Bool { return matchOne(c: 91, consume: consume) // [ } public mutating func eatCloseBracket() -> Bool { return matchCloseBracket(consume: true) } // ] public mutating func matchCloseBracket(consume: Bool = false) -> Bool { return matchOne(c: 93, consume: consume) // ] } public mutating func eatOpenBrace() -> Bool { return matchOpenBrace(consume: true) } // { public mutating func matchOpenBrace(consume: Bool = false) -> Bool { return matchOne(c: 123, consume: consume) // { } public mutating func eatCloseBrace() -> Bool { return matchCloseBrace(consume: true) } // } public mutating func matchCloseBrace(consume: Bool = false) -> Bool { return matchOne(c: 125, consume: consume) // } } public mutating func eatEqual() -> Bool { return matchEqual(consume: true) } // = public mutating func matchEqual(consume: Bool = false) -> Bool { return matchOne(c: 61, consume: consume) // = } public mutating func eatPlus() -> Bool { return matchPlus(consume: true) } // + public mutating func matchPlus(consume: Bool = false) -> Bool { return matchOne(c: 43, consume: consume) // + } public mutating func eatMinus() -> Bool { return matchMinus(consume: true) } // - public mutating func matchMinus(consume: Bool = false) -> Bool { return matchOne(c: 45, consume: consume) // - } public mutating func eatExclamation() -> Bool { return matchExclamation(consume: true) } // ! public mutating func matchExclamation(consume: Bool = false) -> Bool { return matchOne(c: 33, consume: consume) // ! } public mutating func eatQuestionMark() -> Bool { return matchQuestionMark(consume: true) } // ? public mutating func matchQuestionMark(consume: Bool = false) -> Bool { return matchOne(c: 63, consume: consume) // ? } public mutating func eatAmpersand() -> Bool { return matchAmpersand(consume: true) } // & public mutating func matchAmpersand(consume: Bool = false) -> Bool { return matchOne(c: 38, consume: consume) // & } public mutating func eatSemicolon() -> Bool { return matchSemicolon(consume: true) } // ; public mutating func matchSemicolon(consume: Bool = false) -> Bool { return matchOne(c: 59, consume: consume) // ; } public mutating func eatColon() -> Bool { return matchColon(consume: true) } // : public mutating func matchColon(consume: Bool = false) -> Bool { return matchOne(c: 58, consume: consume) // : } public mutating func eatPoint() -> Bool { return matchPoint(consume: true) } // . public mutating func matchPoint(consume: Bool = false) -> Bool { return matchOne(c: 46, consume: consume) // . } public mutating func eatComma() -> Bool { return matchComma(consume: true) } // , public mutating func matchComma(consume: Bool = false) -> Bool { return matchOne(c: 44, consume: consume) // , } public mutating func eatAsterisk() -> Bool { return matchAsterisk(consume: true) } // * public mutating func matchAsterisk(consume: Bool = false) -> Bool { return matchOne(c: 42, consume: consume) // * } public mutating func eatSlash() -> Bool { return matchSlash(consume: true) } // / public mutating func matchSlash(consume: Bool = false) -> Bool { return matchOne(c: 47, consume: consume) // / } public mutating func eatBackslash() -> Bool { return matchBackslash(consume: true) } // \. public mutating func matchBackslash(consume: Bool = false) -> Bool { return matchOne(c: 92, consume: consume) // \. } public mutating func eatAt() -> Bool { return matchAt(consume: true) } // @ public mutating func matchAt(consume: Bool = false) -> Bool { return matchOne(c: 64, consume: consume) // @ } public mutating func eatTilde() -> Bool { return matchTilde(consume: true) } // ~ public mutating func matchTilde(consume: Bool = false) -> Bool { return matchOne(c: 126, consume: consume) // ~ } public mutating func eatUnderline() -> Bool { return matchUnderline(consume: true) } // _ public mutating func matchUnderline(consume: Bool = false) -> Bool { return matchOne(c: 95, consume: consume) // _ } public mutating func eatPercent() -> Bool { return matchPercent(consume: true) } // % public mutating func matchPercent(consume: Bool = false) -> Bool { return matchOne(c: 37, consume: consume) // % } public mutating func eatDollar() -> Bool { return matchDollar(consume: true) } // $ public mutating func matchDollar(consume: Bool = false) -> Bool { return matchOne(c: 36, consume: consume) // $ } public mutating func eatSingleQuote() -> Bool { return matchSingleQuote(consume: true) } // ' public mutating func matchSingleQuote(consume: Bool = false) -> Bool { return matchOne(c: 39, consume: consume) // ' } public mutating func eatDoubleQuote() -> Bool { return matchDoubleQuote(consume: true) } // " public mutating func matchDoubleQuote(consume: Bool = false) -> Bool { return matchOne(c: 34, consume: consume) // " } public mutating func eatHash() -> Bool { return matchHash(consume: true) } // # public mutating func matchHash(consume: Bool = false) -> Bool { return matchOne(c: 35, consume: consume) // # } public mutating func eatPipe() -> Bool { return matchPipe(consume: true) } // | public mutating func matchPipe(consume: Bool = false) -> Bool { return matchOne(c: 124, consume: consume) // | } public mutating func eatCircumflex() -> Bool { return matchCircumflex(consume: true) } // ^ public mutating func matchCircumflex(consume: Bool = false) -> Bool { return matchOne(c: 94, consume: consume) // ^ } // Extended matching public mutating func eatInQuotes(qc: UInt8) -> Bool { return matchInQuotes(qc: qc, consume: true) >= 0 } public mutating func matchInQuotes(qc: UInt8, consume: Bool = false) -> Int { var i = currentIndex if qc == _bytes[i] { let savei = i let len = lineEndIndex i += 1 while i < len { if _bytes[i] == qc { i += 1 if consume { currentIndex = i } return i - savei } i += 1 } } return -1 } public mutating func eatInEscapedQuotes(qc: UInt8) -> Bool { return matchInEscapedQuotes(qc: qc, consume: true) >= 0 } public mutating func matchInEscapedQuotes(qc: UInt8, consume: Bool = false) -> Int { var i = currentIndex if qc == _bytes[i] { let savei = i let len = lineEndIndex i += 1 while i < len { let c = _bytes[i] if c == 92 { // \. i += 1 } else if c == qc { break } i += 1 } if i < len { i += 1 if consume { currentIndex = i } return i - savei } } return -1 } public mutating func eatUntilEscapedString(string: String) -> Bool { return matchUntilEscapedString(string: string, consume: true) >= 0 } public mutating func matchUntilEscapedString(string: String, consume: Bool = false) -> Int { var r = -1 var i = currentIndex let lei = lineEndIndex var sa = [UInt8](string.utf8) let jlen = sa.count let len = lei - jlen + 1 if i < len { let savei = i var escapeCount = 0 let fc = sa[0] while i < len { let c = _bytes[i] if c == 92 { // \. escapeCount += 1 } else if c == fc && escapeCount % 2 == 0 { var j = 1 while j < jlen { if _bytes[i + j] != sa[j] { break } j += 1 } if j >= jlen { break } } else { escapeCount = 0 } i += 1 } if i > savei { r = i - savei if consume { currentIndex = i } } } else if (i < lei) { r = lei - i if consume { currentIndex = lei } } return r } public mutating func eatEscapingUntil(fn: (c: UInt8) -> Bool) -> Bool { return matchEscapingUntil(consume: true, fn: fn) >= 0 } public mutating func matchEscapingUntil(consume: Bool = false, fn: (c: UInt8) -> Bool) -> Int { var i = currentIndex let len = lineEndIndex let savei = i while i < len { let c = _bytes[i] if c == 92 { // \. i += 1 } else if fn(c: c) { break } i += 1 } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } public mutating func eatKeyword(string: String) -> Bool { return matchKeyword(string: string, consume: true) >= 0 } public mutating func matchKeyword(string: String, consume: Bool = false) -> Int { var r = -1 let sa = [UInt8](string.utf8) let len = sa.count let i = currentIndex if i + len <= lineEndIndex { currentIndex = i + len if matchAlphaUnderlineDigit() < 0 { currentIndex = i r = matchString(string: string) if r >= 0 && consume { currentIndex += len } } else { currentIndex = i } } return r } public mutating func eatKeywordFromList(firstCharTable: FirstCharTable) -> Bool { return matchKeywordFromList(firstCharTable: firstCharTable, consume: true) >= 0 } public mutating func matchKeywordFromList(firstCharTable: FirstCharTable, consume: Bool = false) -> Int { var r = -1 let i = currentIndex let len = lineEndIndex if i < len { if let zz = firstCharTable[Int(_bytes[i])] { let jlen = zz.count var j = 0 var zi = 0 var zlen = 0 while j < jlen { let z = zz[j] zlen = z.count if i + zlen <= len { zi = 1 while zi < zlen { if _bytes[i + zi] != z[zi] { break } zi += 1 } if zi >= zlen { zi = i + zlen if zi < len { let c = _bytes[zi] if !((c >= 65 && c <= 90) || // A-Z (c >= 97 && c <= 122) || // a-z (c >= 48 && c <= 57) || c == 95) { // 0-9 _ break } } } } j += 1 } if j < jlen { r = zi if consume { currentIndex = i + zlen } } } } return r } // Triple quotes sequence public mutating func eatEscapingUntilThree(c1: UInt8, c2: UInt8, c3: UInt8) -> Bool { return matchEscapingUntilThree(c1: c1, c2: c2, c3: c3, consume: true) >= 0 } public mutating func matchEscapingUntilThree(c1: UInt8, c2: UInt8, c3: UInt8, consume: Bool = false) -> Int { var i = currentIndex let savei = i let len = lineEndIndex - 2 var c = _bytes[i] var nc = _bytes[i + 1] while i < len { let nnc = _bytes[i + 2] if c == 92 { // \. i += 1 } else if c == c1 && nc == c2 && nnc == c3 { break } c = nc nc = nnc i += 1 } if i >= len { i = lineEndIndex } if i > savei { if consume { currentIndex = i } return i - savei } return -1 } // String list matching public static func makeFirstCharTable(strings: [String]) -> FirstCharTable { let a: [[UInt8]] = strings.map { $0.bytes } return makeFirstCharTable(list: a) } public static func makeFirstCharTable(list: [[UInt8]]) -> FirstCharTable { let len = list.count var a = FirstCharTable(repeating: nil, count: 256) for i in 0..<len { let za = list[i] let cint = Int(za[0]) if a[cint] != nil { a[cint]!.append(za) } else { a[cint] = [za] } } return a } public mutating func eatBytesFromTable(firstCharTable: FirstCharTable) -> Bool { return matchBytesFromTable(firstCharTable: firstCharTable, consume: true) >= 0 } public mutating func matchBytesFromTable(firstCharTable: FirstCharTable, consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i if i < len { if let a = firstCharTable[Int(_bytes[i])] { if a.count == 0 { if consume { currentIndex = i + 1 } return 1 } BYTES: for b in a { let blen = b.count if i + blen <= len { for bi in 1..<blen { if _bytes[i + bi] != b[bi] { continue BYTES } } i += blen if consume { currentIndex = i } return i - savei } } } } return -1 } public mutating func eatUntilIncludingBytesFromTable( firstCharTable: FirstCharTable) -> Bool { return matchUntilIncludingBytesFromTable(firstCharTable: firstCharTable, consume: true) >= 0 } public mutating func matchUntilIncludingBytesFromTable( firstCharTable: FirstCharTable, consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i AGAIN: while i < len { if let a = firstCharTable[Int(_bytes[i])] { if a.count == 0 { i += 1 if consume { currentIndex = i } return i - savei } BYTES: for b in a { let blen = b.count if i + blen <= len { for bi in 1..<blen { if _bytes[i + bi] != b[bi] { continue BYTES } } } else { continue BYTES } i += blen if consume { currentIndex = i } return i - savei } } i += 1 } return -1 } public mutating func eatUntilIncludingString(string: String) -> Bool { return matchUntilIncludingBytes(bytes: string.bytes, consume: true) >= 0 } public mutating func matchUntilIncludingString(string: String, consume: Bool = false) -> Int { return matchUntilIncludingBytes(bytes: string.bytes, consume: consume) } public mutating func eatUntilIncludingBytes(bytes: [UInt8]) -> Bool { return matchUntilIncludingBytes(bytes: bytes, consume: true) >= 0 } public mutating func matchUntilIncludingBytes(bytes: [UInt8], consume: Bool = false) -> Int { var i = currentIndex let blen = bytes.count let len = lineEndIndex - blen + 1 let fc = bytes[0] let savei = i AGAIN: while i < len { if _bytes[i] == fc { for bi in 1..<blen { if _bytes[i + bi] != bytes[bi] { i += 1 continue AGAIN } } i += blen if consume { currentIndex = i } return i - savei } i += 1 } return -1 } public mutating func eatOneNotFromTable(firstCharTable: FirstCharTable) -> Bool { return matchOneNotFromTable(firstCharTable: firstCharTable, consume: true) != nil } public mutating func matchOneNotFromTable(firstCharTable: FirstCharTable, consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if firstCharTable[Int(c)] == nil { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatOneFromTable(firstCharTable: FirstCharTable) -> Bool { return matchOneFromTable(firstCharTable: firstCharTable, consume: true) != nil } public mutating func matchOneFromTable(firstCharTable: FirstCharTable, consume: Bool = false) -> UInt8? { let i = currentIndex if i < lineEndIndex { let c = _bytes[i] if firstCharTable[Int(c)] != nil { if consume { currentIndex = i + 1 } return c } } return nil } public mutating func eatUntilBytesFromTable(firstCharTable: FirstCharTable) -> Bool { return matchUntilBytesFromTable(firstCharTable: firstCharTable, consume: true) >= 0 } public mutating func matchUntilBytesFromTable( firstCharTable: FirstCharTable, consume: Bool = false) -> Int { var i = currentIndex let len = lineEndIndex let savei = i OUT: while i < len { if let a = firstCharTable[Int(_bytes[i])] { if a.count == 0 { if consume { currentIndex = i } return i - savei } BYTES: for b in a { let blen = b.count if i + blen <= len { for bi in 1..<blen { if _bytes[i + bi] != b[bi] { continue BYTES } } if consume { currentIndex = i } break OUT } } } i += 1 } if i > savei { return i - savei } return -1 } public mutating func eatWhileBytesFromTable(firstCharTable: FirstCharTable) -> Bool { return matchWhileBytesFromTable(firstCharTable: firstCharTable, consume: true) >= 0 } // For byte lists of different sizes, the first byte list added to the table // that is a match will result in a short-circuit so that other matching // byte lists following it may not be considered until the next match loop // starts again. This is regardless of byte list length. public mutating func matchWhileBytesFromTable(firstCharTable: FirstCharTable, consume: Bool = false) -> Int { var r = -1 var i = currentIndex let len = lineEndIndex let savei = i AGAIN: while i < len { if let a = firstCharTable[Int(_bytes[i])] { if a.count == 0 { i += 1 if consume { currentIndex = i } return i - savei } BYTES: for b in a { let blen = b.count if i + blen <= len { for bi in 1..<blen { if _bytes[i + bi] != b[bi] { continue BYTES } } i += blen if consume { currentIndex = i } r = i - savei continue AGAIN } } } break } return r } public mutating func eatStringFromListAtEnd(strings: [String]) -> Bool { let bytes = strings.map { $0.bytes } return matchBytesFromListAtEnd(bytes: bytes, consume: true) >= 0 } public mutating func matchStringFromListAtEnd(strings: [String], consume: Bool = false) -> Int { let bytes = strings.map { $0.bytes } return matchBytesFromListAtEnd(bytes: bytes, consume: false) } public mutating func eatBytesFromListAtEnd(bytes: [[UInt8]]) -> Bool { return matchBytesFromListAtEnd(bytes: bytes, consume: true) >= 0 } public mutating func matchBytesFromListAtEnd(bytes: [[UInt8]], consume: Bool = false) -> Int { let len = lineEndIndex let hostLen = len - currentIndex BYTES: for i in 0..<bytes.count { let a = bytes[i] let alen = a.count if alen <= hostLen { let si = len - alen for j in 0..<alen { if a[j] != _bytes[si + j] { continue BYTES } } if consume { currentIndex = len } return i } } return -1 } mutating func merge(buffer: [UInt8], maxBytes: Int) { let len = _bytes.count let si = startIndex if si >= len { bytes = [UInt8](buffer[0..<maxBytes]) } else { var a = [UInt8](_bytes[si..<len]) a += buffer[0..<maxBytes] let offset = currentIndex - si bytes = a currentIndex = offset } } public static func printAscii(bytes: [UInt8]) { let len = bytes.count var a = [UInt8](repeating: 0, count: len) for i in 0..<len { let c = bytes[i] a[i] = (c == 10 || c == 13 || (c >= 32 && c <= 126)) ? c : 46 } let _ = Stdout.write(bytes: a, max: len) if a[len - 1] != 10 { print("") } } }
2a5ff6c59fd3e2c6b12a672c14e549c6
22.877391
80
0.544243
false
false
false
false
ktmswzw/FeelClient
refs/heads/master
FeelingClient/MVC/VM/MessageViewModel.swift
mit
1
// // MessageViewModel.swift // FeelingClient // // Created by Vincent on 4/5/16. // Copyright © 2016 xecoder. All rights reserved. // import Foundation import SwiftyJSON import Alamofire public class Messages:BaseApi { static let defaultMessages = Messages() var msgs = [MessageBean]() var imagesData: [UIImage]? func addMsg(msg: MessageBean, imags:[UIImage]) { msgs.insert(msg, atIndex:0) } func saveMsg(msg: MessageBean, imags:[UIImage],completeHander: CompletionHandlerType) { if imags.count==0 { self.sendSelf(msg, path: "",complete: completeHander) } else { loader.completionAll(imags) { (r:PhotoUpLoader.Result) -> Void in switch (r) { case .Success(let pathIn): self.sendSelf(msg, path: pathIn as!String,complete: completeHander) break; case .Failure(let error): completeHander(Result.Failure(error)) break; } } } } private func sendSelf(msg: MessageBean,path: String,complete: CompletionHandlerType) { let headers = jwt.getHeader(jwt.token, myDictionary: Dictionary<String,String>()) let params = ["to": msg.to, "limitDate":msg.limitDate, "address":msg.address, "content":msg.content,"question": msg.question, "answer": msg.answer, "photos": path, "burnAfterReading":msg.burnAfterReading, "x": "\(msg.y)", "y":"\(msg.x)"] NetApi().makeCall(Alamofire.Method.POST,section: "messages/send", headers: headers, params: params as? [String : AnyObject] ) { (result:BaseApi.Result) -> Void in complete(result) } } // * @param to 接受人 // * @param x 经度 // * @param y 维度 // * @param page // * @param size // func searchMsg(to: String,x: String,y:String,page:Int,size:Int,completeHander: CompletionHandlerType) { let params = ["to": to,"x": y, "y":x, "page": page,"size":size] NetApi().makeCallArray(Alamofire.Method.POST, section: "messages/search", headers: [:], params: params as? [String:AnyObject]) { (response: Response<[MessageBean], NSError>) -> Void in switch (response.result) { case .Success(let value): self.msgs = value completeHander(Result.Success(self.msgs)) break; case .Failure(let error): completeHander(Result.Failure(error)) break; } } } } class MessageApi:BaseApi{ static let defaultMessages = MessageApi() func verifyMsg(id: String,answer:String,completeHander: CompletionHandlerType) { let params = ["answer":answer] let headers = jwt.getHeader(jwt.token, myDictionary: Dictionary<String,String>()) NetApi().makeCall(Alamofire.Method.GET, section: "messages/validate/\(id)", headers: headers, params: params) { (result:BaseApi.Result) -> Void in switch (result) { case .Success(let value): if let json = value { let myJosn = JSON(json) let code:Int = Int(myJosn["status"].stringValue)! let id:String = myJosn.dictionary!["message"]!.stringValue if code != 200 { completeHander(Result.Failure(id)) } else{ completeHander(Result.Success(id)) } } break; case .Failure(let error): print("\(error)") break; } } } func arrival(id: String,completeHander: CompletionHandlerType) { let params = [:] NetApi().makeCallBean(Alamofire.Method.GET, section: "messages/openOver/\(id)", headers: [:], params: (params as! [String : AnyObject])) { (res:Response<MessagesSecret, NSError>) in switch (res.result) { case .Success(let value): completeHander(Result.Success(value)) break case .Failure(let error): completeHander(Result.Failure(error)) break } } } }
7a10e1b9b0fa36232a87fece7aeb0746
34.328
246
0.539298
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
UITests/AuthenticationTests.swift
mpl-2.0
7
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import EarlGrey class AuthenticationTests: KIFTestCase { fileprivate var webRoot: String! override func setUp() { super.setUp() webRoot = SimplePageServer.start() BrowserUtils.configEarlGrey() BrowserUtils.dismissFirstRunUI() } override func tearDown() { BrowserUtils.resetToAboutHome() BrowserUtils.clearPrivateData() super.tearDown() } /** * Tests HTTP authentication credentials and auto-fill. */ func testAuthentication() { loadAuthPage() tester().wait(forTimeInterval: 3) // Make sure that 3 invalid credentials result in authentication failure. enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "foo", password: "bar") enterCredentials(usernameValue: "foo", passwordValue: "•••", username: "foo2", password: "bar2") enterCredentials(usernameValue: "foo2", passwordValue: "••••", username: "foo3", password: "bar3") // Use KIFTest framework for checking elements within webView tester().waitForWebViewElementWithAccessibilityLabel("auth fail") // Enter valid credentials and ensure the page loads. EarlGrey.selectElement(with: grey_accessibilityLabel("Reload")) .perform(grey_tap()) enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass") tester().waitForWebViewElementWithAccessibilityLabel("logged in") // Save the credentials. tester().tapView(withAccessibilityIdentifier: "SaveLoginPrompt.saveLoginButton") logOut() loadAuthPage() // Make sure the credentials were saved and auto-filled. EarlGrey.selectElement(with: grey_accessibilityLabel("Log in")) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .perform(grey_tap()) tester().waitForWebViewElementWithAccessibilityLabel("logged in") // Add a private tab. if BrowserUtils.iPad() { EarlGrey.selectElement(with:grey_accessibilityID("TopTabsViewController.tabsButton")) .perform(grey_tap()) } else { EarlGrey.selectElement(with:grey_accessibilityID("TabToolbar.tabsButton")) .perform(grey_tap()) } EarlGrey.selectElement(with:grey_accessibilityID("TabTrayController.maskButton")) .perform(grey_tap()) EarlGrey.selectElement(with:grey_accessibilityID("TabTrayController.addTabButton")) .perform(grey_tap()) tester().waitForAnimationsToFinish() loadAuthPage() // Make sure the auth prompt is shown. // Note that in the future, we might decide to auto-fill authentication credentials in private browsing mode, // but that's not currently supported. We assume the username and password fields are empty. enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass") tester().waitForWebViewElementWithAccessibilityLabel("logged in") } fileprivate func loadAuthPage() { tester().wait(forTimeInterval: 3) BrowserUtils.enterUrlAddressBar(typeUrl: "\(webRoot!)/auth.html") } fileprivate func logOut() { BrowserUtils.enterUrlAddressBar(typeUrl: "\(webRoot!)/auth.html?logout=1") // Wait until the dialog shows up let dialogAppeared = GREYCondition(name: "Wait the login dialog to appear", block: { var errorOrNil: NSError? let matcher = grey_allOf([grey_accessibilityLabel("Cancel"), grey_sufficientlyVisible()]) EarlGrey.selectElement(with: matcher) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success }).wait(withTimeout: 20) GREYAssertTrue(dialogAppeared, reason: "Failed to display login dialog") EarlGrey.selectElement(with: grey_accessibilityLabel("Cancel")) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .perform(grey_tap()) } fileprivate func enterCredentials(usernameValue: String, passwordValue: String, username: String, password: String) { // In case of IPad, Earl Grey complains that UI Loop has not been finished for password field, reverting. let usernameField = tester().waitForViewWithAccessibilityValue(usernameValue) as! UITextField let passwordField = tester().waitForViewWithAccessibilityValue(passwordValue) as! UITextField usernameField.text = username passwordField.text = password tester().tapView(withAccessibilityLabel: "Log in") } }
8c1042ba7b1e62f213e5dbcf29b0bd96
42.868421
121
0.685663
false
true
false
false
bermudadigitalstudio/Redshot
refs/heads/master
Sources/RedShot/RedisSocket.swift
mit
1
// // This source file is part of the RedShot open source project // // Copyright (c) 2017 Bermuda Digital Studio // Licensed under MIT // // See https://github.com/bermudadigitalstudio/Redshot/blob/master/LICENSE for license information // // Created by Laurent Gaches on 12/06/2017. // import Foundation #if os(Linux) import Glibc #else import Darwin #endif class RedisSocket { private let socketDescriptor: Int32 private let bufferSize: Int init(hostname: String, port: Int, bufferSize: Int) throws { self.bufferSize = bufferSize var hints = addrinfo() hints.ai_family = AF_UNSPEC hints.ai_protocol = Int32(IPPROTO_TCP) hints.ai_flags = AI_PASSIVE #if os(Linux) hints.ai_socktype = Int32(SOCK_STREAM.rawValue) #else hints.ai_socktype = SOCK_STREAM #endif var serverinfo: UnsafeMutablePointer<addrinfo>? = nil defer { if serverinfo != nil { freeaddrinfo(serverinfo) } } let status = getaddrinfo(hostname, port.description, &hints, &serverinfo) do { try RedisSocket.decodeAddrInfoStatus(status: status) } catch { freeaddrinfo(serverinfo) throw error } guard let addrInfo = serverinfo else { throw RedisError.connection("hostname or port not reachable") } // Create the socket descriptor socketDescriptor = socket(addrInfo.pointee.ai_family, addrInfo.pointee.ai_socktype, addrInfo.pointee.ai_protocol) guard socketDescriptor >= 0 else { throw RedisError.connection("Cannot Connect") } // set socket options var optval = 1 #if os(Linux) let statusSocketOpt = setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, &optval, socklen_t(MemoryLayout<Int>.stride)) #else let statusSocketOpt = setsockopt(socketDescriptor, SOL_SOCKET, SO_NOSIGPIPE, &optval, socklen_t(MemoryLayout<Int>.stride)) #endif do { try RedisSocket.decodeSetSockOptStatus(status: statusSocketOpt) } catch { #if os(Linux) _ = Glibc.close(self.socketDescriptor) #else _ = Darwin.close(self.socketDescriptor) #endif throw error } // Connect #if os(Linux) let connStatus = Glibc.connect(socketDescriptor, addrInfo.pointee.ai_addr, addrInfo.pointee.ai_addrlen) try RedisSocket.decodeConnectStatus(connStatus: connStatus) #else let connStatus = Darwin.connect(socketDescriptor, addrInfo.pointee.ai_addr, addrInfo.pointee.ai_addrlen) try RedisSocket.decodeConnectStatus(connStatus: connStatus) #endif } func read() -> Data { var data = Data() let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) var readFlags: Int32 = 0 buffer.initialize(to: 0x0) var read = 0 #if os(Linux) read = Glibc.recv(self.socketDescriptor, buffer, Int(UInt16.max), readFlags) #else read = Darwin.recv(self.socketDescriptor, buffer, Int(UInt16.max), readFlags) #endif if read > 0 { data.append(buffer, count: read) } defer { buffer.deallocate(capacity: 4096) } return data } @discardableResult func send(buffer: UnsafeRawPointer, bufferSize: Int) -> Int { var sent = 0 var sendFlags: Int32 = 0 while sent < bufferSize { var s = 0 #if os(Linux) s = Glibc.send(self.socketDescriptor, buffer.advanced(by: sent), Int(bufferSize - sent), sendFlags) #else s = Darwin.send(self.socketDescriptor, buffer.advanced(by: sent), Int(bufferSize - sent), sendFlags) #endif sent += s } return sent } @discardableResult func send(data: Data) throws -> Int { guard !data.isEmpty else { return 0} return try data.withUnsafeBytes { [unowned self](buffer: UnsafePointer<UInt8>) throws -> Int in return self.send(buffer: buffer, bufferSize: data.count) } } @discardableResult func send(string: String) -> Int { return string.utf8CString.withUnsafeBufferPointer { return self.send(buffer: $0.baseAddress!, bufferSize: $0.count - 1) } } func close() { #if os(Linux) _ = Glibc.close(self.socketDescriptor) #else _ = Darwin.close(self.socketDescriptor) #endif } var isConnected: Bool { var error = 0 var len: socklen_t = 4 getsockopt(self.socketDescriptor, SOL_SOCKET, SO_ERROR, &error, &len) guard error == 0 else { return false } return true } deinit { close() } static func decodeAddrInfoStatus(status: Int32) throws { if status != 0 { var strError: String if status == EAI_SYSTEM { strError = String(validatingUTF8: strerror(errno)) ?? "Unknown error code" } else { strError = String(validatingUTF8: gai_strerror(status)) ?? "Unknown error code" } throw RedisError.connection(strError) } } static func decodeSetSockOptStatus(status: Int32) throws { if status == -1 { let strError = String(utf8String: strerror(errno)) ?? "Unknown error code" let message = "Setsockopt error \(errno) \(strError)" throw RedisError.connection(message) } } static func decodeConnectStatus(connStatus: Int32) throws { if connStatus != 0 { let strError = String(utf8String: strerror(errno)) ?? "Unknown error code" let message = "Setsockopt error \(errno) \(strError)" throw RedisError.connection("can't connect : \(connStatus) message : \(message)") } } }
871831898d1be4e461f28f417e8dfc90
29.222222
116
0.577526
false
false
false
false
MostafaTaghipour/mtpFontManager
refs/heads/master
mtpFontManager/Classes/Constants.swift
mit
1
// // Constants.swift // mtpFontManager // // Created by Mostafa Taghipour on 2/9/19. // import Foundation struct Constants { /// The name of the attribute that Dynamic Type uses when a text style is /// set in Interface Builder. static let dynamicTextAttribute = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute") static let plistType = "plist" static let fontIdFiled = "id" static let fontFamilyNameFiled = "family name" static let fontDefaultFiled = "default" }
4095440a9d85bc29df2f03c73d3f09e8
26.473684
107
0.712644
false
false
false
false
ton-katsu/SimpleAlertController
refs/heads/master
SimpleAlertControllerExample/SimpleAlertControllerExample/NothingViewController.swift
mit
1
// // NothingViewController.swift // SimpleAlertViewControllerExample // // Created by yoshihisa on 2015/04/13. // Copyright (c) 2015年 ton-katsu. All rights reserved. // import UIKit class NothingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton() button.setTitle("SimpleAlertController", for: UIControlState()) button.backgroundColor = UIColor.black button.addTarget(self, action: #selector(NothingViewController.cloud(_:)), for: UIControlEvents.touchUpInside) button.frame = CGRect(x: 0, y: 0, width: 200, height: 50) button.center = view.center view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func cloud(_ button: UIButton) { let alert = SimpleAlertController(title: "Cloud", message: "color scheme", colorScheme: SimpleAlertColorScheme.cloud) let cancel = SimpleAlertAction(title: "Cancel", style: SimpleAlertActionStyle.cancel, handler: {() -> Void in print("Cancel(;_;)")}) let moveTab = SimpleAlertAction(title: "Move", style: SimpleAlertActionStyle.default, handler: {() -> Void in self.tabBarController?.selectedIndex = 2 print("Moved") }) let destructive = SimpleAlertAction(title: "Destrctive", style: SimpleAlertActionStyle.destructive, handler: nil) alert.addAction(moveTab) alert.addAction(destructive) alert.addAction(cancel) tabBarController?.simplePresentViewController(alert, animated: true) } }
4709d1b4b11ca86ac732c5a9f70b254f
36.840909
140
0.667267
false
false
false
false
Pretz/SwiftGraphics
refs/heads/develop
SwiftGraphics/Geometry/Circle.swift
bsd-2-clause
2
// // Circle.swift // SwiftGraphics // // Created by Jonathan Wight on 1/16/15. // Copyright (c) 2015 schwa.io. All rights reserved. // import CoreGraphics // MARK: Circle public struct Circle { public let center: CGPoint public let radius: CGFloat public var diameter: CGFloat { return radius * 2 } public init(center: CGPoint = CGPointZero, radius: CGFloat) { self.center = center self.radius = radius } public init(center: CGPoint = CGPointZero, diameter: CGFloat) { self.center = center self.radius = diameter * 0.5 } } extension Circle: Geometry { public var frame: CGRect { return CGRect(center: center, diameter: diameter) } } extension Circle { // TODO: Just convert into an ellipse. func toBezierCurves() -> (BezierCurve, BezierCurve, BezierCurve, BezierCurve) { let quadrants = [ CGSize(w: -1.0, h: -1.0), CGSize(w: 1.0, h: -1.0), CGSize(w: -1.0, h: 1.0), CGSize(w: 1.0, h: 1.0), ] let d = radius * 4.0 * (sqrt(2.0) - 1.0) / 3.0 // Create a cubic bezier curve for the each quadrant of the circle... // Note this does not draw the curves either clockwise or anti-clockwise - and not suitable for use in a bezier path. var curves = quadrants.map() { (quadrant: CGSize) -> BezierCurve in return BezierCurve( start: self.center + CGPoint(x: self.radius) * quadrant, control1: self.center + (CGPoint(x: self.radius) + CGPoint(y: d)) * quadrant, control2: self.center + (CGPoint(y: self.radius) + CGPoint(x: d)) * quadrant, end: self.center + CGPoint(y: self.radius) * quadrant ) } // TODO: Converting into an array and then a tuple is silly. return (curves[0], curves[1], curves[2], curves[3]) } }
2c12696178a1635b2cca5514c0488909
28.815385
125
0.580495
false
false
false
false
tlax/tlaxcala
refs/heads/master
Tlaxcala/View/Main/VSpinner.swift
mit
1
import UIKit class VSpinner:UIImageView { private let kAnimationDuration:TimeInterval = 0.7 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ #imageLiteral(resourceName: "assetSpinner0"), #imageLiteral(resourceName: "assetSpinner1"), #imageLiteral(resourceName: "assetSpinner2"), #imageLiteral(resourceName: "assetSpinner3") ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder:NSCoder) { return nil } }
0397477df55dd38de8e868ddf9593c81
25.032258
57
0.6171
false
false
false
false
andreipitis/ASPCircleChart
refs/heads/master
Sources/ASPCircleChartSliceLayer.swift
mit
1
// // CircleChartSliceLayer.swift // ASPCircleChart // // Created by Andrei-Sergiu Pițiș on 15/06/16. // Copyright © 2016 Andrei-Sergiu Pițiș. All rights reserved. // import UIKit /** Custom layer that draws a slice of a circle. */ open class ASPCircleChartSliceLayer: CALayer { /** The start angle in radians of the slice. */ @NSManaged open var startAngle: CGFloat /** The end angle in radians of the slice. */ @NSManaged open var endAngle: CGFloat /** The color of the slice. */ open var strokeColor: UIColor = UIColor.black /** The width of the slice. Default value is 10.0. */ open var strokeWidth: CGFloat = 10.0 /** The duration of the slice animation. Default value is 0.35. */ open var animationDuration: Double = 0.35 /** The value that will be subtracted from the slice radius. */ open var radiusOffset: CGFloat = 0.0 /** The cap style of the slice. */ open var lineCapStyle: CGLineCap = .butt public override init() { super.init() contentsScale = UIScreen.main.scale } public override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale if let layer = layer as? ASPCircleChartSliceLayer { startAngle = layer.startAngle endAngle = layer.endAngle strokeColor = layer.strokeColor strokeWidth = layer.strokeWidth lineCapStyle = layer.lineCapStyle animationDuration = layer.animationDuration radiusOffset = layer.radiusOffset } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func draw(in ctx: CGContext) { super.draw(in: ctx) UIGraphicsPushContext(ctx) let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY) let radius = min(centerPoint.x, centerPoint.y) - (strokeWidth / 2.0) - radiusOffset let bezierPath = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) strokeColor.setStroke() bezierPath.lineWidth = strokeWidth bezierPath.lineCapStyle = lineCapStyle bezierPath.stroke() UIGraphicsPopContext() } open override func action(forKey event: String) -> CAAction? { if event == "startAngle" || event == "endAngle" { let basicAnimation = CABasicAnimation(keyPath: event) basicAnimation.fromValue = presentation()?.value(forKey: event) basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut) basicAnimation.duration = animationDuration return basicAnimation } return super.action(forKey: event) } open override class func needsDisplay(forKey key: String) -> Bool { if key == "startAngle" || key == "endAngle" { return true } return super.needsDisplay(forKey: key) } }
4e11acfe7b9bb5ea0c3360228469317d
23.115044
132
0.708257
false
false
false
false
vmanot/swift-package-manager
refs/heads/master
Sources/Basic/Process.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import class Foundation.ProcessInfo import enum POSIX.SystemError import func POSIX.getenv import libc import Dispatch /// Process result data which is available after process termination. public struct ProcessResult: CustomStringConvertible { public enum Error: Swift.Error { /// The output is not a valid UTF8 sequence. case illegalUTF8Sequence /// The process had a non zero exit. case nonZeroExit(ProcessResult) } public enum ExitStatus { /// The process was terminated normally with a exit code. case terminated(code: Int32) /// The process was terminated due to a signal. case signalled(signal: Int32) } /// The arguments with which the process was launched. public let arguments: [String] /// The exit status of the process. public let exitStatus: ExitStatus /// The output bytes of the process. Available only if the process was /// asked to redirect its output. public let output: Result<[Int8], AnyError> /// The output bytes of the process. Available only if the process was /// asked to redirect its output. public let stderrOutput: Result<[Int8], AnyError> /// Create an instance using the process exit code and output result. fileprivate init( arguments: [String], exitStatus: Int32, output: Result<[Int8], AnyError>, stderrOutput: Result<[Int8], AnyError> ) { self.arguments = arguments self.output = output self.stderrOutput = stderrOutput if WIFSIGNALED(exitStatus) { self.exitStatus = .signalled(signal: WTERMSIG(exitStatus)) } else { precondition(WIFEXITED(exitStatus), "unexpected exit status \(exitStatus)") self.exitStatus = .terminated(code: WEXITSTATUS(exitStatus)) } } /// Converts stdout output bytes to string, assuming they're UTF8. /// /// - Throws: Error while reading the process output or if output is not a valid UTF8 sequence. public func utf8Output() throws -> String { return try utf8Result(output) } /// Converts stderr output bytes to string, assuming they're UTF8. /// /// - Throws: Error while reading the process output or if output is not a valid UTF8 sequence. public func utf8stderrOutput() throws -> String { return try utf8Result(stderrOutput) } /// Returns UTF8 string from given result or throw. private func utf8Result(_ result: Result<[Int8], AnyError>) throws -> String { var bytes = try result.dematerialize() // Null terminate it. bytes.append(0) if let output = String(validatingUTF8: bytes) { return output } throw Error.illegalUTF8Sequence } public var description: String { return """ <ProcessResult: exit: \(exitStatus), output: \((try? utf8Output()) ?? "") > """ } } /// Process allows spawning new subprocesses and working with them. /// /// Note: This class is thread safe. public final class Process: ObjectIdentifierProtocol { /// Errors when attempting to invoke a process public enum Error: Swift.Error { /// The program requested to be executed cannot be found on the existing search paths, or is not executable. case missingExecutableProgram(program: String) } /// Typealias for process id type. public typealias ProcessID = pid_t /// Global default setting for verbose. public static var verbose = false /// If true, prints the subprocess arguments before launching it. public let verbose: Bool /// The current environment. static public var env: [String: String] { return ProcessInfo.processInfo.environment } /// The arguments to execute. public let arguments: [String] /// The environment with which the process was executed. public let environment: [String: String] /// The process id of the spawned process, available after the process is launched. public private(set) var processID = ProcessID() /// If the subprocess has launched. /// Note: This property is not protected by the serial queue because it is only mutated in `launch()`, which will be /// called only once. public private(set) var launched = false /// The result of the process execution. Available after process is terminated. public var result: ProcessResult? { return self.serialQueue.sync { self._result } } /// If process was asked to redirect its output. public let redirectOutput: Bool /// The result of the process execution. Available after process is terminated. private var _result: ProcessResult? /// If redirected, stdout result and reference to the thread reading the output. private var stdout: (result: Result<[Int8], AnyError>, thread: Thread?) = (Result([]), nil) /// If redirected, stderr result and reference to the thread reading the output. private var stderr: (result: Result<[Int8], AnyError>, thread: Thread?) = (Result([]), nil) /// Queue to protect concurrent reads. private let serialQueue = DispatchQueue(label: "org.swift.swiftpm.process") /// Queue to protect reading/writing on map of validated executables. private static let executablesQueue = DispatchQueue( label: "org.swift.swiftpm.process.findExecutable") /// Cache of validated executables. /// /// Key: Executable name or path. /// Value: If key was found in the search paths and is executable. static private var validatedExecutablesMap = [String: Bool]() /// Create a new process instance. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - redirectOutput: Redirect and store stdout/stderr output (of subprocess) in the process result, instead of /// printing on the standard streams. Default value is true. /// - verbose: If true, launch() will print the arguments of the subprocess before launching it. public init( arguments: [String], environment: [String: String] = env, redirectOutput: Bool = true, verbose: Bool = Process.verbose ) { self.arguments = arguments self.environment = environment self.redirectOutput = redirectOutput self.verbose = verbose } /// Returns true if the given program is present and executable in search path. /// /// The program can be executable name, relative path or absolute path. func findExecutable(_ program: String) -> Bool { return Process.executablesQueue.sync { // Check if we already have a value for the program. if let value = Process.validatedExecutablesMap[program] { return value } // FIXME: This can be cached. let envSearchPaths = getEnvSearchPaths( pathString: getenv("PATH"), currentWorkingDirectory: currentWorkingDirectory ) // Lookup the executable. let value = lookupExecutablePath( filename: program, searchPaths: envSearchPaths) != nil Process.validatedExecutablesMap[program] = value return value } } /// Launch the subprocess. public func launch() throws { precondition(arguments.count > 0 && !arguments[0].isEmpty, "Need at least one argument to launch the process.") precondition(!launched, "It is not allowed to launch the same process object again.") // Set the launch bool to true. launched = true // Print the arguments if we are verbose. if self.verbose { stdoutStream <<< arguments.map({ $0.shellEscaped() }).joined(separator: " ") <<< "\n" stdoutStream.flush() } // Look for executable. guard findExecutable(arguments[0]) else { throw Process.Error.missingExecutableProgram(program: arguments[0]) } // Initialize the spawn attributes. #if os(macOS) var attributes: posix_spawnattr_t? = nil #else var attributes = posix_spawnattr_t() #endif posix_spawnattr_init(&attributes) // Unmask all signals. var noSignals = sigset_t() sigemptyset(&noSignals) posix_spawnattr_setsigmask(&attributes, &noSignals) // Reset all signals to default behavior. #if os(macOS) var mostSignals = sigset_t() sigfillset(&mostSignals) sigdelset(&mostSignals, SIGKILL) sigdelset(&mostSignals, SIGSTOP) posix_spawnattr_setsigdefault(&attributes, &mostSignals) #else // On Linux, this can only be used to reset signals that are legal to // modify, so we have to take care about the set we use. var mostSignals = sigset_t() sigemptyset(&mostSignals) for i in 1 ..< SIGUNUSED { if i == SIGKILL || i == SIGSTOP { continue } sigaddset(&mostSignals, i) } posix_spawnattr_setsigdefault(&attributes, &mostSignals) #endif // Establish a separate process group. posix_spawnattr_setpgroup(&attributes, 0) // Set the attribute flags. var flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF flags |= POSIX_SPAWN_SETPGROUP posix_spawnattr_setflags(&attributes, Int16(flags)) // Setup the file actions. #if os(macOS) var fileActions: posix_spawn_file_actions_t? = nil #else var fileActions = posix_spawn_file_actions_t() #endif posix_spawn_file_actions_init(&fileActions) // Workaround for https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=89e435f3559c53084498e9baad22172b64429362 let devNull = strdup("/dev/null") defer { free(devNull) } // Open /dev/null as stdin. posix_spawn_file_actions_addopen(&fileActions, 0, devNull, O_RDONLY, 0) var outputPipe: [Int32] = [0, 0] var stderrPipe: [Int32] = [0, 0] if redirectOutput { // Open the pipes. try open(pipe: &outputPipe) try open(pipe: &stderrPipe) // Open the write end of the pipe as stdout and stderr, if desired. posix_spawn_file_actions_adddup2(&fileActions, outputPipe[1], 1) posix_spawn_file_actions_adddup2(&fileActions, stderrPipe[1], 2) // Close the other ends of the pipe. for pipe in [outputPipe, stderrPipe] { posix_spawn_file_actions_addclose(&fileActions, pipe[0]) posix_spawn_file_actions_addclose(&fileActions, pipe[1]) } } else { posix_spawn_file_actions_adddup2(&fileActions, 1, 1) posix_spawn_file_actions_adddup2(&fileActions, 2, 2) } let argv = CStringArray(arguments) let env = CStringArray(environment.map({ "\($0.0)=\($0.1)" })) let rv = posix_spawnp(&processID, argv.cArray[0], &fileActions, &attributes, argv.cArray, env.cArray) guard rv == 0 else { throw SystemError.posix_spawn(rv, arguments) } posix_spawn_file_actions_destroy(&fileActions) posix_spawnattr_destroy(&attributes) if redirectOutput { // Close the write end of the output pipe. try close(fd: &outputPipe[1]) // Create a thread and start reading the output on it. var thread = Thread { self.stdout.result = self.readOutput(onFD: outputPipe[0]) } thread.start() self.stdout.thread = thread // Close the write end of the stderr pipe. try close(fd: &stderrPipe[1]) // Create a thread and start reading the stderr output on it. thread = Thread { self.stderr.result = self.readOutput(onFD: stderrPipe[0]) } thread.start() self.stderr.thread = thread } } /// Blocks the calling process until the subprocess finishes execution. @discardableResult public func waitUntilExit() throws -> ProcessResult { return try serialQueue.sync { precondition(launched, "The process is not yet launched.") // If the process has already finsihed, return it. if let existingResult = _result { return existingResult } // If we're reading output, make sure that is finished. stdout.thread?.join() stderr.thread?.join() // Wait until process finishes execution. var exitStatus: Int32 = 0 var result = waitpid(processID, &exitStatus, 0) while result == -1 && errno == EINTR { result = waitpid(processID, &exitStatus, 0) } if result == -1 { throw SystemError.waitpid(errno) } // Construct the result. let executionResult = ProcessResult( arguments: arguments, exitStatus: exitStatus, output: stdout.result, stderrOutput: stderr.result ) self._result = executionResult return executionResult } } /// Reads the given fd and returns its result. /// /// Closes the fd before returning. private func readOutput(onFD fd: Int32) -> Result<[Int8], AnyError> { // Read all of the data from the output pipe. let N = 4096 var buf = [Int8](repeating: 0, count: N + 1) var out = [Int8]() var error: Swift.Error? = nil loop: while true { let n = read(fd, &buf, N) switch n { case -1: if errno == EINTR { continue } else { error = SystemError.read(errno) break loop } case 0: break loop default: out += buf[0..<n] } } // Close the read end of the output pipe. close(fd) // Construct the output result. return error.map(Result.init) ?? Result(out) } /// Send a signal to the process. /// /// Note: This will signal all processes in the process group. public func signal(_ signal: Int32) { assert(launched, "The process is not yet launched.") _ = libc.kill(-processID, signal) } } extension Process { /// Execute a subprocess and block until it finishes execution /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - Returns: The process result. @discardableResult static public func popen(arguments: [String], environment: [String: String] = env) throws -> ProcessResult { let process = Process(arguments: arguments, environment: environment, redirectOutput: true) try process.launch() return try process.waitUntilExit() } @discardableResult static public func popen(args: String..., environment: [String: String] = env) throws -> ProcessResult { return try Process.popen(arguments: args, environment: environment) } /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - Returns: The process output (stdout + stderr). @discardableResult static public func checkNonZeroExit(arguments: [String], environment: [String: String] = env) throws -> String { let process = Process(arguments: arguments, environment: environment, redirectOutput: true) try process.launch() let result = try process.waitUntilExit() // Throw if there was a non zero termination. guard result.exitStatus == .terminated(code: 0) else { throw ProcessResult.Error.nonZeroExit(result) } return try result.utf8Output() } @discardableResult static public func checkNonZeroExit(args: String..., environment: [String: String] = env) throws -> String { return try checkNonZeroExit(arguments: args, environment: environment) } public convenience init(args: String..., environment: [String: String] = env, redirectOutput: Bool = true) { self.init(arguments: args, environment: environment, redirectOutput: redirectOutput) } } // MARK: - Private helpers #if os(macOS) private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #else private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t #endif private func WIFEXITED(_ status: Int32) -> Bool { return _WSTATUS(status) == 0 } private func _WSTATUS(_ status: Int32) -> Int32 { return status & 0x7f } private func WIFSIGNALED(_ status: Int32) -> Bool { return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f) } private func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xff } private func WTERMSIG(_ status: Int32) -> Int32 { return status & 0x7f } extension ProcessResult.ExitStatus: Equatable { public static func == (lhs: ProcessResult.ExitStatus, rhs: ProcessResult.ExitStatus) -> Bool { switch (lhs, rhs) { case (.terminated(let l), .terminated(let r)): return l == r case (.terminated(_), _): return false case (.signalled(let l), .signalled(let r)): return l == r case (.signalled(_), _): return false } } } /// Open the given pipe. private func open(pipe: inout [Int32]) throws { let rv = libc.pipe(&pipe) guard rv == 0 else { throw SystemError.pipe(rv) } } /// Close the given fd. private func close(fd: inout Int32) throws { let rv = libc.close(fd) guard rv == 0 else { throw SystemError.close(rv) } } extension Process.Error: CustomStringConvertible { public var description: String { switch self { case .missingExecutableProgram(let program): return "could not find executable for '\(program)'" } } } extension ProcessResult.Error: CustomStringConvertible { public var description: String { switch self { case .illegalUTF8Sequence: return "illegal UTF8 sequence output" case .nonZeroExit(let result): let stream = BufferedOutputByteStream() switch result.exitStatus { case .terminated(let code): stream <<< "terminated(\(code)): " case .signalled(let signal): stream <<< "signalled(\(signal)): " } // Strip sandbox information from arguments to keep things pretty. var args = result.arguments // This seems a little fragile. if args.first == "sandbox-exec", args.count > 3 { args = args.suffix(from: 3).map({$0}) } stream <<< args.map({ $0.shellEscaped() }).joined(separator: " ") return stream.bytes.asString! } } }
c63e9f6c2c908bb03e42bbcbaa66708f
34.396825
120
0.615247
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Floral/Classes/Base/View/TableView.swift
mit
1
// // TableView.swift // Floral // // Created by LDD on 2019/7/18. // Copyright © 2019 文刂Rn. All rights reserved. // import UIKit class TableView: UITableView { override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { estimatedRowHeight = 50 rowHeight = UITableView.automaticDimension backgroundColor = .clear if #available(iOS 9.0, *) { cellLayoutMarginsFollowReadableWidth = false } keyboardDismissMode = .onDrag separatorStyle = .none } func updateUI() { setNeedsDisplay() } }
3fccb6a793457eb7021401ccc615a181
20.702703
60
0.596513
false
false
false
false
zzeleznick/piazza-clone
refs/heads/master
Pizzazz/Pizzazz/HeaderViewCell.swift
mit
1
// // HeaderViewCell.swift // Pizzazz // // Created by Zach Zeleznick on 5/6/16. // Copyright © 2016 zzeleznick. All rights reserved. // import Foundation import UIKit class HeaderViewCell: UITableViewCell { let titleLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let w = UIScreen.main.bounds.size.width contentView.backgroundColor = UIColor(rgb: 0xeff0f1) contentView.addUIElement(titleLabel, frame: CGRect(x: 30, y: 6, width: w-30, height: 20)) {element in guard let label = element as? UILabel else { return } let font = UIFont(name: "HelveticaNeue", size: 13) label.font = font } } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } }
26949d0aff977732cd6bdf663f8ba2f2
28.064516
110
0.644839
false
false
false
false
ajthom90/FontAwesome.swift
refs/heads/master
Demo/FontAwesomeDemo/ViewController.swift
mit
1
// ViewController.swift // // Copyright (c) 2014-present FontAwesome.swift contributors // // 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 FontAwesome class ViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! @IBOutlet weak var barButton: UIBarButtonItem! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var imageViewColored: UIImageView! @IBOutlet weak var toolbarItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // FontAwesome icon in label label.font = UIFont.fontAwesome(ofSize: 100) label.text = String.fontAwesomeIcon(name: FontAwesome.github) let attributes = [NSAttributedStringKey.font: UIFont.fontAwesome(ofSize: 20)] // FontAwesome icon in button button.titleLabel?.font = UIFont.fontAwesome(ofSize: 30) button.setTitle(String.fontAwesomeIcon(name: .github), for: .normal) // FontAwesome icon as navigation bar item barButton.setTitleTextAttributes(attributes, for: .normal) barButton.title = String.fontAwesomeIcon(name: .github) // FontAwesome icon as toolbar item toolbarItem.setTitleTextAttributes(attributes, for: .normal) toolbarItem.title = String.fontAwesomeIcon(name: .github) // FontAwesome icon as image imageView.image = UIImage.fontAwesomeIcon(name: FontAwesome.github, textColor: UIColor.black, size: CGSize(width: 4000, height: 4000)) // FontAwesome icon as image with background color imageViewColored.image = UIImage.fontAwesomeIcon(name: FontAwesome.github, textColor: UIColor.blue, size: CGSize(width: 4000, height: 4000), backgroundColor: UIColor.red) } }
e7081cea011722def3cb0a37e6ab3bcd
43.571429
178
0.735755
false
false
false
false
shirai/SwiftLearning
refs/heads/master
playground/オプショナルの連鎖.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit /* * * * */ class Person { let name: String var friends: [Person]? init(name: String) { self.name = name } } let taro = Person(name: "タロウ") print(taro.friends?.count) if let friends = taro.friends { print(friends.count) } /* 映画館クラス */ class MovieTheater { let name: String var screens: [Screen]? // イニシャライザ init(_ name: String) { self.name = name } } /* スクリーンクラス */ class Screen { var movie: Movie? // 映画 var sheets: [Bool] // 座席 // 各座席にアクセスするためのサブスクリプト subscript(idx: Int) -> Bool { get { return sheets[idx] } set { sheets[idx] = newValue } } // 座席数 var numberOfSheets: Int { return sheets.count } // イニシャライザ init(numberOfSheets: Int) { self.sheets = Array(repeating: false, count: numberOfSheets) } } /* 映画クラス */ class Movie { var title: String // タイトル var director: String? // 監督 var leadingActors: String? // 主演 // イニシャライザ init(_ title: String) { self.title = title } // 説明 func printDescription() { print("タイトル:\(title)") if let director = self.director { print(" 監督:\(director)") } if let leadingActors = self.leadingActors { print(" 主演:\(leadingActors)") } print() } } //映画館クラスのインスタンス let theater = MovieTheater("りんごシアター") //スクリーン数(スクリーンの配列はオプショナル型)をオプショナルの連鎖を使って安全に取得 if let numScreens = theater.screens?.count { print("\(theater.name)のスクリーン数は\(numScreens)です。") } else { print("\(theater.name)にスクリーンは有りません。") } // スクリーンA let screenA = Screen(numberOfSheets: 150) let dieHard = Movie("ダイ・ハード") dieHard.director = "ジョン・マクティアナン" dieHard.leadingActors = "ブルース・ウィリス" screenA.movie = dieHard // スクリーンB let screenB = Screen(numberOfSheets: 200) let terminator = Movie("ターミネーター") terminator.director = "ジェームズ・キャメロン" terminator.leadingActors = "アーノルド・シュワルツェネッガー" screenB.movie = terminator theater.screens = [screenA, screenB] if let numScreens = theater.screens?.count { print("\(theater.name)のスクリーン数は\(numScreens)です。") } else { print("\(theater.name)にスクリーンは有りません。") } //最初のスクリーンの上映映画のタイトルを表示 if let title = theater.screens?[0].movie?.title { print(title) } //オプショナルの連鎖を使わない場合、階層の途中のオプショナル型の数が増えるほどアンラップの確認のための記述が増え if let screens = theater.screens { if let movie = screens[0].movie { print(movie.title) } } //2番目のスクリーンの、25番目のシートの空席状況を調べる if let sheet = theater.screens?[1][24] { print(sheet ? "埋まってます。" : "空席です。") } theater.screens?[1][24] = true if let sheet = theater.screens?[1][24] { print(sheet ? "埋まってます。" : "空席です。") } //最初のスクリーンの映画監督を出力 if let director = theater.screens?[0].movie?.director { print(director) } //値の変更 theater.screens?[0].movie?.director = "ジョン・マクティアナン(John McTiernan)" if (theater.screens?[0].movie?.director = "ジョン・マクティアナン(John McTiernan)") != nil { print("監督名を変更しました。") //もし連鎖のいずれかのオプショナル型がnilのため値を変更できない場合は、nilが返される } //インスタンスメソッドの呼び出し theater.screens?[1].movie?.printDescription() if theater.screens?[1].movie?.printDescription() != nil { print("メソッドは実行されました。") //オプショナルの連鎖の途中がnilだった場合、メソッドは実行されない。 //値を返さないメソッドの戻り値の型はVoidであるため、オプショナルの連鎖によるメソッド呼び出しの型はVoid?となる。 } if let method = theater.screens?[1].movie?.printDescription { method() } //事前にメソッドが実行可能かどうかを確認したい場合は、次のようにメソッド自体を戻り値としてアンラップ後実行する //theater.screens?[1].movie?.printDescription から返される型は、printDescriptionメソッドの型 () -> () のオプショナル型 let method: (() -> ())? = theater.screens?[1].movie?.printDescription if (method != nil) { method!() }
67bc9d84db9eae00a477ec437205a696
22.474684
95
0.639795
false
false
false
false
ChenJian345/realm-cocoa
refs/heads/master
Pods/RealmSwift/RealmSwift/Migration.swift
apache-2.0
15
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** Migration block used to migrate a Realm. :param: migration `Migration` object used to perform the migration. The migration object allows you to enumerate and alter any existing objects which require migration. :param: oldSchemaVersion The schema version of the `Realm` being migrated. */ public typealias MigrationBlock = (migration: Migration, oldSchemaVersion: UInt64) -> Void /// Object class used during migrations public typealias MigrationObject = DynamicObject /** Provides both the old and new versions of an object in this Realm. Objects properties can only be accessed using subscripting. :param: oldObject Object in original `Realm` (read-only) :param: newObject Object in migrated `Realm` (read-write) */ public typealias MigrationObjectEnumerateBlock = (oldObject: MigrationObject?, newObject: MigrationObject?) -> Void /** Specify a schema version and an associated migration block which is applied when opening the default Realm with an old schema version. Before you can open an existing `Realm` which has a different on-disk schema from the schema defined in your object interfaces, you must provide a migration block which converts from the disk schema to your current object schema. At the minimum your migration block must initialize any properties which were added to existing objects without defaults and ensure uniqueness if a primary key property is added to an existing object. You should call this method before accessing any `Realm` instances which require migration. After registering your migration block, Realm will call your block automatically as needed. :warning: Unsuccessful migrations will throw exceptions when the migration block is applied. This will happen in the following cases: - The given `schemaVersion` is lower than the target Realm's current schema version. - A new property without a default was added to an object and not initialized during the migration. You are required to either supply a default value or to manually populate added properties during a migration. :param: version The current schema version. :param: block The block which migrates the Realm to the current version. */ public func setDefaultRealmSchemaVersion(schemaVersion: UInt64, migrationBlock: MigrationBlock) { RLMRealm.setDefaultRealmSchemaVersion(schemaVersion, withMigrationBlock: accessorMigrationBlock(migrationBlock)) } /** Specify a schema version and an associated migration block which is applied when opening a Realm at the specified path with an old schema version. Before you can open an existing `Realm` which has a different on-disk schema from the schema defined in your object interfaces, you must provide a migration block which converts from the disk schema to your current object schema. At the minimum your migration block must initialize any properties which were added to existing objects without defaults and ensure uniqueness if a primary key property is added to an existing object. You should call this method before accessing any `Realm` instances which require migration. After registering your migration block, Realm will call your block automatically as needed. :param: version The current schema version. :param: realmPath The path of the Realms to migrate. :param: block The block which migrates the Realm to the current version. */ public func setSchemaVersion(schemaVersion: UInt64, realmPath: String, migrationBlock: MigrationBlock) { RLMRealm.setSchemaVersion(schemaVersion, forRealmAtPath: realmPath, withMigrationBlock: accessorMigrationBlock(migrationBlock)) } /** Get the schema version for a Realm at a given path. :param: realmPath Path to a Realm file. :param: encryptionKey Optional 64-byte encryption key for encrypted Realms. :param: error If an error occurs, upon return contains an `NSError` object that describes the problem. If you are not interested in possible errors, omit the argument, or pass in `nil`. :returns: The version of the Realm at `realmPath` or `nil` if the version cannot be read. */ public func schemaVersionAtPath(realmPath: String, encryptionKey: NSData? = nil, error: NSErrorPointer = nil) -> UInt64? { let version = RLMRealm.schemaVersionAtPath(realmPath, encryptionKey: encryptionKey, error: error) if version == RLMNotVersioned { return nil } return version } /** Performs the registered migration block on a Realm at the given path. This method is called automatically when opening a Realm for the first time and does not need to be called explicitly. You can choose to call this method to control exactly when and how migrations are performed. :param: path The path of the Realm to migrate. :param: encryptionKey Optional 64-byte encryption key for encrypted Realms. If the Realms at the given path are not encrypted, omit the argument or pass in `nil`. :returns: `nil` if the migration was successful, or an `NSError` object that describes the problem that occured otherwise. */ public func migrateRealm(path: String, encryptionKey: NSData? = nil) -> NSError? { if let encryptionKey = encryptionKey { return RLMRealm.migrateRealmAtPath(path, encryptionKey: encryptionKey) } else { return RLMRealm.migrateRealmAtPath(path) } } /** `Migration` is the object passed into a user-defined `MigrationBlock` when updating the version of a `Realm` instance. This object provides access to the previous and current `Schema`s for this migration. */ public final class Migration { // MARK: Properties /// The migration's old `Schema`, describing the `Realm` before applying a migration. public var oldSchema: Schema { return Schema(rlmMigration.oldSchema) } /// The migration's new `Schema`, describing the `Realm` after applying a migration. public var newSchema: Schema { return Schema(rlmMigration.newSchema) } private var rlmMigration: RLMMigration // MARK: Altering Objects During a Migration /** Enumerates objects of a given type in this Realm, providing both the old and new versions of each object. Object properties can be accessed using subscripting. :param: className The name of the `Object` class to enumerate. :param: block The block providing both the old and new versions of an object in this Realm. */ public func enumerate(objectClassName: String, _ block: MigrationObjectEnumerateBlock) { rlmMigration.enumerateObjects(objectClassName) { block(oldObject: unsafeBitCast($0, MigrationObject.self), newObject: unsafeBitCast($1, MigrationObject.self)) } } /** Create an `Object` of type `className` in the Realm being migrated. :param: className The name of the `Object` class to create. :param: object The object used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. :returns: The created object. */ public func create(className: String, value: AnyObject = [:]) -> MigrationObject { return unsafeBitCast(rlmMigration.createObject(className, withValue: value), MigrationObject.self) } /** Delete an object from a Realm during a migration. This can be called within `enumerate(_:block:)`. :param: object Object to be deleted from the Realm being migrated. */ public func delete(object: MigrationObject) { RLMDeleteObjectFromRealm(object, RLMObjectBaseRealm(object)) } /** Deletes the data for the class with the given name. This deletes all objects of the given class, and if the Object subclass no longer exists in your program, cleans up any remaining metadata for the class in the Realm file. :param: name The name of the Object class to delete. :returns: whether there was any data to delete. */ public func deleteData(objectClassName: String) -> Bool { return rlmMigration.deleteDataForClassName(objectClassName) } private init(_ rlmMigration: RLMMigration) { self.rlmMigration = rlmMigration } } // MARK: Private Helpers private func accessorMigrationBlock(migrationBlock: MigrationBlock) -> RLMMigrationBlock { return { migration, oldVersion in // set all accessor classes to MigrationObject for objectSchema in migration.oldSchema.objectSchema { if let objectSchema = objectSchema as? RLMObjectSchema { objectSchema.accessorClass = MigrationObject.self // isSwiftClass is always `false` for object schema generated // from the table, but we need to pretend it's from a swift class // (even if it isn't) for the accessors to be initialized correctly. objectSchema.isSwiftClass = true } } for objectSchema in migration.newSchema.objectSchema { if let objectSchema = objectSchema as? RLMObjectSchema { objectSchema.accessorClass = MigrationObject.self } } // run migration migrationBlock(migration: Migration(migration), oldSchemaVersion: oldVersion) } }
63e772b5e73d14894a891d9020f62618
42.35
131
0.716167
false
false
false
false
tensorflow/swift-apis
refs/heads/main
Sources/x10/swift_bindings/XLAScalarType.swift
apache-2.0
1
// Copyright 2020 TensorFlow Authors // // 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. @_implementationOnly import x10_xla_tensor_wrapper extension XLAScalar { init(_ v: Double) { self.init() self.tag = XLAScalarTypeTag_d self.value.d = v } init(_ v: Int64) { self.init() self.tag = XLAScalarTypeTag_i self.value.i = v } } public enum XLAScalarWrapper { public init(_ v: Double) { self = .d(v) } public init(_ v: Int64) { self = .i(v) } case d(Double) case i(Int64) var xlaScalar: XLAScalar { switch self { case .d(let v): return XLAScalar(v) case .i(let v): return XLAScalar(v) } } } /// A supported datatype in x10. public protocol XLAScalarType { var xlaScalarWrapper: XLAScalarWrapper { get } static var xlaTensorScalarTypeRawValue: UInt32 { get } } extension XLAScalarType { var xlaScalar: XLAScalar { xlaScalarWrapper.xlaScalar } static var xlaTensorScalarType: XLATensorScalarType { #if os(Windows) return XLATensorScalarType(rawValue: Int32(xlaTensorScalarTypeRawValue)) #else return XLATensorScalarType(rawValue: UInt32(xlaTensorScalarTypeRawValue)) #endif } } extension Float: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Double(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Float.rawValue) } } extension Double: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(self) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Double.rawValue) } } extension Int64: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(self) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int64.rawValue) } } extension Int32: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int32.rawValue) } } extension Int16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int16.rawValue) } } extension Int8: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int8.rawValue) } } extension UInt8: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_UInt8.rawValue) } } extension Bool: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self ? 1 : 0)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Bool.rawValue) } } /// Error implementations extension BFloat16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("BFloat16 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_BFloat16.rawValue) } } extension UInt64: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt64 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt64 not suported") } } extension UInt32: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt32 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt32 not suported") } } extension UInt16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt16 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt16 not suported") } }
79b48231814db80858b051fadc126e73
28.490196
89
0.750222
false
false
false
false
atrick/swift
refs/heads/main
test/Generics/generic_types.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on protocol MyFormattedPrintable { func myFormat() -> String } func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {} extension Int : MyFormattedPrintable { func myFormat() -> String { return "" } } struct S<T : MyFormattedPrintable> { var c : T static func f(_ a: T) -> T { return a } func f(_ a: T, b: Int) { return myPrintf("%v %v %v", a, b, c) } } func makeSInt() -> S<Int> {} typealias SInt = S<Int> var a : S<Int> = makeSInt() a.f(1,b: 2) var b : Int = SInt.f(1) struct S2<T> { @discardableResult static func f() -> T { S2.f() } } struct X { } var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}} enum Optional<T> { case element(T) case none init() { self = .none } init(_ t: T) { self = .element(t) } } typealias OptionalInt = Optional<Int> var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element var uniontest2 : Optional<Int> = OptionalInt.none var uniontest3 = OptionalInt(1) // FIXME: Stuff that should work, but doesn't yet. // var uniontest4 : OptInt = .none // var uniontest5 : OptInt = .Some(1) func formattedTest<T : MyFormattedPrintable>(_ a: T) { myPrintf("%v", a) } struct formattedTestS<T : MyFormattedPrintable> { func f(_ a: T) { formattedTest(a) } } struct GenericReq<T : IteratorProtocol, U : IteratorProtocol> where T.Element == U.Element { } func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element { var r = r return r.next()! } func testGetFirst(ir: Range<Int>) { _ = getFirst(ir.makeIterator()) as Int } struct XT<T> { init(t : T) { prop = (t, t) } static func f() -> T {} func g() -> T {} var prop : (T, T) } class YT<T> { init(_ t : T) { prop = (t, t) } deinit {} class func f() -> T {} func g() -> T {} var prop : (T, T) } struct ZT<T> { var x : T, f : Float } struct Dict<K, V> { subscript(key: K) -> V { get {} set {} } } class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}} subscript(key: K) -> V { get {} set {} } } typealias XI = XT<Int> typealias YI = YT<Int> typealias ZI = ZT<Int> var xi = XI(t: 17) var yi = YI(17) var zi = ZI(x: 1, f: 3.0) var i : Int = XI.f() i = XI.f() i = xi.g() i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}} i = yi.g() var xif : (XI) -> () -> Int = XI.g var gif : (YI) -> () -> Int = YI.g var ii : (Int, Int) = xi.prop ii = yi.prop xi.prop = ii yi.prop = ii var d1 : Dict<String, Int> var d2 : Dictionary<String, Int> d1["hello"] = d2["world"] i = d2["blarg"] struct RangeOfPrintables<R : Sequence> where R.Iterator.Element : MyFormattedPrintable { var r : R func format() -> String { var s : String for e in r { s = s + e.myFormat() + " " } return s } } struct Y {} struct SequenceY : Sequence, IteratorProtocol { typealias Iterator = SequenceY typealias Element = Y func next() -> Element? { return Y() } func makeIterator() -> Iterator { return self } } func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) { var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}} var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}} } var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}} var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}} var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}} // Make sure that redundant typealiases (that map to the same // underlying type) don't break protocol conformance or use. class XArray : ExpressibleByArrayLiteral { typealias Element = Int init() { } required init(arrayLiteral elements: Int...) { } } class YArray : XArray { typealias Element = Int required init(arrayLiteral elements: Int...) { super.init() } } var yarray : YArray = [1, 2, 3] var xarray : XArray = [1, 2, 3] // Type parameters can be referenced only via unqualified name lookup struct XParam<T> { // expected-note{{'XParam' declared here}} func foo(_ x: T) { _ = x as T } static func bar(_ x: T) { _ = x as T } } var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of generic struct 'generic_types.XParam<Swift.Int>'}} // Diagnose failure to meet a superclass requirement. class X1 { } class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}} class X3 { } var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}} protocol P { associatedtype AssocP } protocol Q { associatedtype AssocQ } struct X4 : P, Q { typealias AssocP = Int typealias AssocQ = String } struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}} var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}} // Recursive generic signature validation. class Top {} class Bottom<T : Bottom<Top>> {} // expected-error@-1 {{'Bottom' requires that 'Top' inherit from 'Bottom<Top>'}} // expected-note@-2 {{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}} // expected-error@-3 *{{generic class 'Bottom' has self-referential generic requirements}} // Invalid inheritance clause struct UnsolvableInheritance1<T : T.A> {} // expected-error@-1 {{'A' is not a member type of type 'T'}} // expected-error@-2 {{type 'T' constrained to non-protocol, non-class type 'T.A'}} struct UnsolvableInheritance2<T : U.A, U : T.A> {} // expected-error@-1 {{'A' is not a member type of type 'U'}} // expected-error@-2 {{'A' is not a member type of type 'T'}} // expected-error@-3 {{type 'T' constrained to non-protocol, non-class type 'U.A'}} // expected-error@-4 {{type 'U' constrained to non-protocol, non-class type 'T.A'}} enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}} // expected-error@-1{{cannot find type 'G' in scope}} // Test that contextual type resolution for generic metatypes is consistent // under a same-type constraint. protocol MetatypeTypeResolutionProto {} struct X8<T> { static var property1: T.Type { T.self } static func method1() -> T.Type { T.self } } extension X8 where T == MetatypeTypeResolutionProto { static var property2: T.Type { property1 } // ok, still .Protocol static func method2() -> T.Type { method1() } // ok, still .Protocol }
93f7a873ad800cc46f6e535d6780fa09
25.134615
148
0.643414
false
false
false
false
aschwaighofer/swift
refs/heads/master
stdlib/public/core/Range.swift
apache-2.0
7
//===--- Range.swift ------------------------------------------*- 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 // //===----------------------------------------------------------------------===// /// A type that can be used to slice a collection. /// /// A type that conforms to `RangeExpression` can convert itself to a /// `Range<Bound>` of indices within a given collection. public protocol RangeExpression { /// The type for which the expression describes a range. associatedtype Bound: Comparable /// Returns the range of indices described by this range expression within /// the given collection. /// /// You can use the `relative(to:)` method to convert a range expression, /// which could be missing one or both of its endpoints, into a concrete /// range that is bounded on both sides. The following example uses this /// method to convert a partial range up to `4` into a half-open range, /// using an array instance to add the range's lower bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// let upToFour = ..<4 /// /// let r1 = upToFour.relative(to: numbers) /// // r1 == 0..<4 /// /// The `r1` range is bounded on the lower end by `0` because that is the /// starting index of the `numbers` array. When the collection passed to /// `relative(to:)` starts with a different index, that index is used as the /// lower bound instead. The next example creates a slice of `numbers` /// starting at index `2`, and then uses the slice with `relative(to:)` to /// convert `upToFour` to a concrete range. /// /// let numbersSuffix = numbers[2...] /// // numbersSuffix == [30, 40, 50, 60, 70] /// /// let r2 = upToFour.relative(to: numbersSuffix) /// // r2 == 2..<4 /// /// Use this method only if you need the concrete range it produces. To /// access a slice of a collection using a range expression, use the /// collection's generic subscript that uses a range expression as its /// parameter. /// /// let numbersPrefix = numbers[upToFour] /// // numbersPrefix == [10, 20, 30, 40] /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound /// Returns a Boolean value indicating whether the given element is contained /// within the range expression. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range expression; /// otherwise, `false`. func contains(_ element: Bound) -> Bool } extension RangeExpression { @inlinable public static func ~= (pattern: Self, value: Bound) -> Bool { return pattern.contains(value) } } /// A half-open interval from a lower bound up to, but not including, an upper /// bound. /// /// You create a `Range` instance by using the half-open range operator /// (`..<`). /// /// let underFive = 0.0..<5.0 /// /// You can use a `Range` instance to quickly check if a value is contained in /// a particular range of values. For example: /// /// underFive.contains(3.14) /// // true /// underFive.contains(6.28) /// // false /// underFive.contains(5.0) /// // false /// /// `Range` instances can represent an empty interval, unlike `ClosedRange`. /// /// let empty = 0.0..<0.0 /// empty.contains(0.0) /// // false /// empty.isEmpty /// // true /// /// Using a Range as a Collection of Consecutive Values /// ---------------------------------------------------- /// /// When a range uses integers as its lower and upper bounds, or any other type /// that conforms to the `Strideable` protocol with an integer stride, you can /// use that range in a `for`-`in` loop or with any sequence or collection /// method. The elements of the range are the consecutive values from its /// lower bound up to, but not including, its upper bound. /// /// for n in 3..<5 { /// print(n) /// } /// // Prints "3" /// // Prints "4" /// /// Because floating-point types such as `Float` and `Double` are their own /// `Stride` types, they cannot be used as the bounds of a countable range. If /// you need to iterate over consecutive floating-point values, see the /// `stride(from:to:by:)` function. @frozen public struct Range<Bound: Comparable> { /// The range's lower bound. /// /// In an empty range, `lowerBound` is equal to `upperBound`. public let lowerBound: Bound /// The range's upper bound. /// /// In an empty range, `upperBound` is equal to `lowerBound`. A `Range` /// instance does not contain its upper bound. public let upperBound: Bound /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the half-open range operator /// (`..<`) to form `Range` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @inlinable public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// Because `Range` represents a half-open range, a `Range` instance does not /// contain its upper bound. `element` is contained in the range if it is /// greater than or equal to the lower bound and less than the upper bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @inlinable public func contains(_ element: Bound) -> Bool { return lowerBound <= element && element < upperBound } /// A Boolean value indicating whether the range contains no elements. /// /// An empty `Range` instance has equal lower and upper bounds. /// /// let empty: Range = 10..<10 /// print(empty.isEmpty) /// // Prints "true" @inlinable public var isEmpty: Bool { return lowerBound == upperBound } } extension Range: Sequence where Bound: Strideable, Bound.Stride: SignedInteger { public typealias Element = Bound public typealias Iterator = IndexingIterator<Range<Bound>> } extension Range: Collection, BidirectionalCollection, RandomAccessCollection where Bound: Strideable, Bound.Stride: SignedInteger { /// A type that represents a position in the range. public typealias Index = Bound public typealias Indices = Range<Bound> public typealias SubSequence = Range<Bound> @inlinable public var startIndex: Index { return lowerBound } @inlinable public var endIndex: Index { return upperBound } @inlinable public func index(after i: Index) -> Index { _failEarlyRangeCheck(i, bounds: startIndex..<endIndex) return i.advanced(by: 1) } @inlinable public func index(before i: Index) -> Index { _precondition(i > lowerBound) _precondition(i <= upperBound) return i.advanced(by: -1) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { let r = i.advanced(by: numericCast(n)) _precondition(r >= lowerBound) _precondition(r <= upperBound) return r } @inlinable public func distance(from start: Index, to end: Index) -> Int { return numericCast(start.distance(to: end)) } /// Accesses the subsequence bounded by the given range. /// /// - Parameter bounds: A range of the range's indices. The upper and lower /// bounds of the `bounds` range must be valid indices of the collection. @inlinable public subscript(bounds: Range<Index>) -> Range<Bound> { return bounds } /// The indices that are valid for subscripting the range, in ascending /// order. @inlinable public var indices: Indices { return self } @inlinable public func _customContainsEquatableElement(_ element: Element) -> Bool? { return lowerBound <= element && element < upperBound } @inlinable public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? { return lowerBound <= element && element < upperBound ? element : nil } @inlinable public func _customLastIndexOfEquatableElement(_ element: Bound) -> Index?? { // The first and last elements are the same because each element is unique. return _customIndexOfEquatableElement(element) } /// Accesses the element at specified position. /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the range, and must not equal the range's end /// index. @inlinable public subscript(position: Index) -> Element { // FIXME: swift-3-indexing-model: tests for the range check. _debugPrecondition(self.contains(position), "Index out of range") return position } } extension Range where Bound: Strideable, Bound.Stride: SignedInteger { /// Creates an instance equivalent to the given `ClosedRange`. /// /// - Parameter other: A closed range to convert to a `Range` instance. /// /// An equivalent range must be representable as an instance of Range<Bound>. /// For example, passing a closed range with an upper bound of `Int.max` /// triggers a runtime error, because the resulting half-open range would /// require an upper bound of `Int.max + 1`, which is not representable as public init(_ other: ClosedRange<Bound>) { let upperBound = other.upperBound.advanced(by: 1) self.init(uncheckedBounds: (lower: other.lowerBound, upper: upperBound)) } } extension Range: RangeExpression { /// Returns the range of indices described by this range expression within /// the given collection. /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. @inlinable // trivial-implementation public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return Range(uncheckedBounds: (lower: lowerBound, upper: upperBound)) } } extension Range { /// Returns a copy of this range clamped to the given limiting range. /// /// The bounds of the result are always limited to the bounds of `limits`. /// For example: /// /// let x: Range = 0..<20 /// print(x.clamped(to: 10..<1000)) /// // Prints "10..<20" /// /// If the two ranges do not overlap, the result is an empty range within the /// bounds of `limits`. /// /// let y: Range = 0..<5 /// print(y.clamped(to: 10..<1000)) /// // Prints "10..<10" /// /// - Parameter limits: The range to clamp the bounds of this range. /// - Returns: A new range clamped to the bounds of `limits`. @inlinable // trivial-implementation @inline(__always) public func clamped(to limits: Range) -> Range { let lower = limits.lowerBound > self.lowerBound ? limits.lowerBound : limits.upperBound < self.lowerBound ? limits.upperBound : self.lowerBound let upper = limits.upperBound < self.upperBound ? limits.upperBound : limits.lowerBound > self.upperBound ? limits.lowerBound : self.upperBound return Range(uncheckedBounds: (lower: lower, upper: upper)) } } extension Range: CustomStringConvertible { /// A textual representation of the range. @inlinable // trivial-implementation public var description: String { return "\(lowerBound)..<\(upperBound)" } } extension Range: CustomDebugStringConvertible { /// A textual representation of the range, suitable for debugging. public var debugDescription: String { return "Range(\(String(reflecting: lowerBound))" + "..<\(String(reflecting: upperBound)))" } } extension Range: CustomReflectable { public var customMirror: Mirror { return Mirror( self, children: ["lowerBound": lowerBound, "upperBound": upperBound]) } } extension Range: Equatable { /// Returns a Boolean value indicating whether two ranges are equal. /// /// Two ranges are equal when they have the same lower and upper bounds. /// That requirement holds even for empty ranges. /// /// let x = 5..<15 /// print(x == 5..<15) /// // Prints "true" /// /// let y = 5..<5 /// print(y == 15..<15) /// // Prints "false" /// /// - Parameters: /// - lhs: A range to compare. /// - rhs: Another range to compare. @inlinable public static func == (lhs: Range<Bound>, rhs: Range<Bound>) -> Bool { return lhs.lowerBound == rhs.lowerBound && lhs.upperBound == rhs.upperBound } } extension Range: Hashable where Bound: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(lowerBound) hasher.combine(upperBound) } } extension Range: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let lowerBound = try container.decode(Bound.self) let upperBound = try container.decode(Bound.self) guard lowerBound <= upperBound else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Range.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))")) } self.init(uncheckedBounds: (lower: lowerBound, upper: upperBound)) } } extension Range: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.lowerBound) try container.encode(self.upperBound) } } /// A partial half-open interval up to, but not including, an upper bound. /// /// You create `PartialRangeUpTo` instances by using the prefix half-open range /// operator (prefix `..<`). /// /// let upToFive = ..<5.0 /// /// You can use a `PartialRangeUpTo` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use a `PartialRangeUpTo` instance of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" @frozen public struct PartialRangeUpTo<Bound: Comparable> { public let upperBound: Bound @inlinable // trivial-implementation public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeUpTo: RangeExpression { @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<self.upperBound } @_transparent public func contains(_ element: Bound) -> Bool { return element < upperBound } } extension PartialRangeUpTo: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeUpTo: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.upperBound) } } /// A partial interval up to, and including, an upper bound. /// /// You create `PartialRangeThrough` instances by using the prefix closed range /// operator (prefix `...`). /// /// let throughFive = ...5.0 /// /// You can use a `PartialRangeThrough` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use a `PartialRangeThrough` instance of a collection's indices to /// represent the range from the start of the collection up to, and including, /// the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" @frozen public struct PartialRangeThrough<Bound: Comparable> { public let upperBound: Bound @inlinable // trivial-implementation public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeThrough: RangeExpression { @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<collection.index(after: self.upperBound) } @_transparent public func contains(_ element: Bound) -> Bool { return element <= upperBound } } extension PartialRangeThrough: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeThrough: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.upperBound) } } /// A partial interval extending upward from a lower bound. /// /// You create `PartialRangeFrom` instances by using the postfix range operator /// (postfix `...`). /// /// let atLeastFive = 5... /// /// You can use a partial range to quickly check if a value is contained in a /// particular range of values. For example: /// /// atLeastFive.contains(4) /// // false /// atLeastFive.contains(5) /// // true /// atLeastFive.contains(6) /// // true /// /// You can use a partial range of a collection's indices to represent the /// range from the partial range's lower bound up to the end of the /// collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// Using a Partial Range as a Sequence /// ----------------------------------- /// /// When a partial range uses integers as its lower and upper bounds, or any /// other type that conforms to the `Strideable` protocol with an integer /// stride, you can use that range in a `for`-`in` loop or with any sequence /// method that doesn't require that the sequence is finite. The elements of /// a partial range are the consecutive values from its lower bound continuing /// upward indefinitely. /// /// func isTheMagicNumber(_ x: Int) -> Bool { /// return x == 3 /// } /// /// for x in 1... { /// if isTheMagicNumber(x) { /// print("\(x) is the magic number!") /// break /// } else { /// print("\(x) wasn't it...") /// } /// } /// // "1 wasn't it..." /// // "2 wasn't it..." /// // "3 is the magic number!" /// /// Because a `PartialRangeFrom` sequence counts upward indefinitely, do not /// use one with methods that read the entire sequence before returning, such /// as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations /// that put an upper limit on the number of elements they access, such as /// `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee /// will terminate, such as passing a closure you know will eventually return /// `true` to `first(where:)`. /// /// In the following example, the `asciiTable` sequence is made by zipping /// together the characters in the `alphabet` string with a partial range /// starting at 65, the ASCII value of the capital letter A. Iterating over /// two zipped sequences continues only as long as the shorter of the two /// sequences, so the iteration stops at the end of `alphabet`. /// /// let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /// let asciiTable = zip(65..., alphabet) /// for (code, letter) in asciiTable { /// print(code, letter) /// } /// // "65 A" /// // "66 B" /// // "67 C" /// // ... /// // "89 Y" /// // "90 Z" /// /// The behavior of incrementing indefinitely is determined by the type of /// `Bound`. For example, iterating over an instance of /// `PartialRangeFrom<Int>` traps when the sequence's next value would be /// above `Int.max`. @frozen public struct PartialRangeFrom<Bound: Comparable> { public let lowerBound: Bound @inlinable // trivial-implementation public init(_ lowerBound: Bound) { self.lowerBound = lowerBound } } extension PartialRangeFrom: RangeExpression { @_transparent public func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound { return self.lowerBound..<collection.endIndex } @inlinable // trivial-implementation public func contains(_ element: Bound) -> Bool { return lowerBound <= element } } extension PartialRangeFrom: Sequence where Bound: Strideable, Bound.Stride: SignedInteger { public typealias Element = Bound /// The iterator for a `PartialRangeFrom` instance. @frozen public struct Iterator: IteratorProtocol { @usableFromInline internal var _current: Bound @inlinable public init(_current: Bound) { self._current = _current } /// Advances to the next element and returns it, or `nil` if no next /// element exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Returns: The next element in the underlying sequence, if a next /// element exists; otherwise, `nil`. @inlinable public mutating func next() -> Bound? { defer { _current = _current.advanced(by: 1) } return _current } } /// Returns an iterator for this sequence. @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_current: lowerBound) } } extension PartialRangeFrom: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeFrom: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.lowerBound) } } extension Comparable { /// Returns a half-open range that contains its lower bound but not its upper /// bound. /// /// Use the half-open range operator (`..<`) to create a range of any type /// that conforms to the `Comparable` protocol. This example creates a /// `Range<Double>` from zero up to, but not including, 5.0. /// /// let lessThanFive = 0.0..<5.0 /// print(lessThanFive.contains(3.14)) // Prints "true" /// print(lessThanFive.contains(5.0)) // Prints "false" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_transparent public static func ..< (minimum: Self, maximum: Self) -> Range<Self> { _precondition(minimum <= maximum, "Can't form Range with upperBound < lowerBound") return Range(uncheckedBounds: (lower: minimum, upper: maximum)) } /// Returns a partial range up to, but not including, its upper bound. /// /// Use the prefix half-open range operator (prefix `..<`) to create a /// partial range of any type that conforms to the `Comparable` protocol. /// This example creates a `PartialRangeUpTo<Double>` instance that includes /// any value less than `5.0`. /// /// let upToFive = ..<5.0 /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" /// /// - Parameter maximum: The upper bound for the range. @_transparent public static prefix func ..< (maximum: Self) -> PartialRangeUpTo<Self> { return PartialRangeUpTo(maximum) } /// Returns a partial range up to, and including, its upper bound. /// /// Use the prefix closed range operator (prefix `...`) to create a partial /// range of any type that conforms to the `Comparable` protocol. This /// example creates a `PartialRangeThrough<Double>` instance that includes /// any value less than or equal to `5.0`. /// /// let throughFive = ...5.0 /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, and /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" /// /// - Parameter maximum: The upper bound for the range. @_transparent public static prefix func ... (maximum: Self) -> PartialRangeThrough<Self> { return PartialRangeThrough(maximum) } /// Returns a partial range extending upward from a lower bound. /// /// Use the postfix range operator (postfix `...`) to create a partial range /// of any type that conforms to the `Comparable` protocol. This example /// creates a `PartialRangeFrom<Double>` instance that includes any value /// greater than or equal to `5.0`. /// /// let atLeastFive = 5.0... /// /// atLeastFive.contains(4.0) // false /// atLeastFive.contains(5.0) // true /// atLeastFive.contains(6.0) // true /// /// You can use this type of partial range of a collection's indices to /// represent the range from the partial range's lower bound up to the end /// of the collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// - Parameter minimum: The lower bound for the range. @_transparent public static postfix func ... (minimum: Self) -> PartialRangeFrom<Self> { return PartialRangeFrom(minimum) } } /// A range expression that represents the entire range of a collection. /// /// You can use the unbounded range operator (`...`) to create a slice of a /// collection that contains all of the collection's elements. Slicing with an /// unbounded range is essentially a conversion of a collection instance into /// its slice type. /// /// For example, the following code declares `countLetterChanges(_:_:)`, a /// function that finds the number of changes required to change one /// word or phrase into another. The function uses a recursive approach to /// perform the same comparisons on smaller and smaller pieces of the original /// strings. In order to use recursion without making copies of the strings at /// each step, `countLetterChanges(_:_:)` uses `Substring`, a string's slice /// type, for its parameters. /// /// func countLetterChanges(_ s1: Substring, _ s2: Substring) -> Int { /// if s1.isEmpty { return s2.count } /// if s2.isEmpty { return s1.count } /// /// let cost = s1.first == s2.first ? 0 : 1 /// /// return min( /// countLetterChanges(s1.dropFirst(), s2) + 1, /// countLetterChanges(s1, s2.dropFirst()) + 1, /// countLetterChanges(s1.dropFirst(), s2.dropFirst()) + cost) /// } /// /// To call `countLetterChanges(_:_:)` with two strings, use an unbounded /// range in each string's subscript. /// /// let word1 = "grizzly" /// let word2 = "grisly" /// let changes = countLetterChanges(word1[...], word2[...]) /// // changes == 2 @frozen // namespace public enum UnboundedRange_ { // FIXME: replace this with a computed var named `...` when the language makes // that possible. /// Creates an unbounded range expression. /// /// The unbounded range operator (`...`) is valid only within a collection's /// subscript. public static postfix func ... (_: UnboundedRange_) -> () { // This function is uncallable } } /// The type of an unbounded range operator. public typealias UnboundedRange = (UnboundedRange_)->() extension Collection { /// Accesses the contiguous subrange of the collection's elements specified /// by a range expression. /// /// The range expression is converted to a concrete subrange relative to this /// collection. For example, using a `PartialRangeFrom` range expression /// with an array accesses the subrange from the start of the range /// expression until the end of the array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2...] /// print(streetsSlice) /// // ["Channing", "Douglas", "Evarts"] /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. This example searches `streetsSlice` for one /// of the strings in the slice, and then uses that index in the original /// array. /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // "Evarts" /// /// Always use the slice's `startIndex` property instead of assuming that its /// indices start at a particular value. Attempting to access an element by /// using an index outside the bounds of the slice's indices may result in a /// runtime error, even if that index is valid for the original collection. /// /// print(streetsSlice.startIndex) /// // 2 /// print(streetsSlice[2]) /// // "Channing" /// /// print(streetsSlice[0]) /// // error: Index out of bounds /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @inlinable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { return self[r.relative(to: self)] } @inlinable public subscript(x: UnboundedRange) -> SubSequence { return self[startIndex...] } } extension MutableCollection { @inlinable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { get { return self[r.relative(to: self)] } set { self[r.relative(to: self)] = newValue } } @inlinable public subscript(x: UnboundedRange) -> SubSequence { get { return self[startIndex...] } set { self[startIndex...] = newValue } } } // TODO: enhance RangeExpression to make this generic and available on // any expression. extension Range { /// Returns a Boolean value indicating whether this range and the given range /// contain an element in common. /// /// This example shows two overlapping ranges: /// /// let x: Range = 0..<20 /// print(x.overlaps(10...1000)) /// // Prints "true" /// /// Because a half-open range does not include its upper bound, the ranges /// in the following example do not overlap: /// /// let y = 20..<30 /// print(x.overlaps(y)) /// // Prints "false" /// /// - Parameter other: A range to check for elements in common. /// - Returns: `true` if this range and `other` have at least one element in /// common; otherwise, `false`. @inlinable public func overlaps(_ other: Range<Bound>) -> Bool { // Disjoint iff the other range is completely before or after our range. // Additionally either `Range` (unlike a `ClosedRange`) could be empty, in // which case it is disjoint with everything as overlap is defined as having // an element in common. let isDisjoint = other.upperBound <= self.lowerBound || self.upperBound <= other.lowerBound || self.isEmpty || other.isEmpty return !isDisjoint } @inlinable public func overlaps(_ other: ClosedRange<Bound>) -> Bool { // Disjoint iff the other range is completely before or after our range. // Additionally the `Range` (unlike the `ClosedRange`) could be empty, in // which case it is disjoint with everything as overlap is defined as having // an element in common. let isDisjoint = other.upperBound < self.lowerBound || self.upperBound <= other.lowerBound || self.isEmpty return !isDisjoint } } // Note: this is not for compatibility only, it is considered a useful // shorthand. TODO: Add documentation public typealias CountableRange<Bound: Strideable> = Range<Bound> where Bound.Stride: SignedInteger // Note: this is not for compatibility only, it is considered a useful // shorthand. TODO: Add documentation public typealias CountablePartialRangeFrom<Bound: Strideable> = PartialRangeFrom<Bound> where Bound.Stride: SignedInteger
b6245ae5e168075450188d521278bffc
34.254862
137
0.655121
false
false
false
false
github/codeql
refs/heads/main
swift/ql/test/library-tests/dataflow/taint/nsmutabledata.swift
mit
1
// --- stubs --- struct Data { init<S>(_ elements: S) {} } struct NSRange {} class NSData {} class NSMutableData : NSData { var mutableBytes: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: 0)! func append(_ bytes: UnsafeRawPointer, length: Int) {} func append(_ other: Data) {} func replaceBytes(in range: NSRange, withBytes bytes: UnsafeRawPointer) {} func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {} func setData(_ data: Data) {} } // --- tests --- func source() -> Any { return "" } func sink(arg: Any) {} func test() { // ";NSMutableData;true;append(_:length:);;;Argument[0];Argument[-1];taint", let nsMutableDataTainted1 = NSMutableData() nsMutableDataTainted1.append(source() as! UnsafeRawPointer, length: 0) sink(arg: nsMutableDataTainted1) // $ tainted=28 // ";MutableNSData;true;append(_:);;;Argument[0];Argument[-1];taint", let nsMutableDataTainted2 = NSMutableData() nsMutableDataTainted2.append(source() as! Data) sink(arg: nsMutableDataTainted2) // $ tainted=32 // ";NSMutableData;true;replaceBytes(in:withBytes:);;;Argument[1];Argument[-1];taint", let nsMutableDataTainted3 = NSMutableData() nsMutableDataTainted3.replaceBytes(in: NSRange(), withBytes: source() as! UnsafeRawPointer) sink(arg: nsMutableDataTainted3) // $ tainted=36 // ";NSMutableData;true;replaceBytes(in:withBytes:length:);;;Argument[1];Argument[-1];taint", let nsMutableDataTainted4 = NSMutableData() nsMutableDataTainted4.replaceBytes(in: NSRange(), withBytes: source() as? UnsafeRawPointer, length: 0) sink(arg: nsMutableDataTainted4) // $ tainted=40 // ";NSMutableData;true;setData(_:);;;Argument[1];Argument[-1];taint", let nsMutableDataTainted5 = NSMutableData() nsMutableDataTainted5.setData(source() as! Data) sink(arg: nsMutableDataTainted5) // $ tainted=44 // Fields let nsMutableDataTainted6 = source() as! NSMutableData sink(arg: nsMutableDataTainted6.mutableBytes) // $ tainted=48 }
020da347cbf6d9f9a7cbb083b4cd265c
40.8
121
0.703828
false
false
false
false
paulgriffiths/macvideopoker
refs/heads/master
VideoPoker/SuitCounter.swift
gpl-3.0
1
// // SuitCounter.swift // // Utility struct to calculate the numbers of distinct suits // in a list of playing cards, for instance to determine how // many clubs or hearts are present in the list. // // Copyright (c) 2015 Paul Griffiths. // Distributed under the terms of the GNU General Public License. <http://www.gnu.org/licenses/> // struct SuitCounter { private var suits: [Suit : Int] = [:] init(cardList: CardList) { for card in cardList { countCard(card) } } var count: Int { return suits.count } mutating private func countCard(card: Card) { if let count = suits[card.suit] { suits[card.suit] = count + 1 } else { suits[card.suit] = 1 } } func containsSuit(suit: Suit) -> Bool { if suits[suit] != nil { return true } else { return false } } func countForSuit(suit: Suit) -> Int { if let count = suits[suit] { return count } else { return 0 } } }
c0bc563c3634cf3797a9ee9a7e4495c7
20.942308
97
0.521053
false
false
false
false
alexames/flatbuffers
refs/heads/master
swift/Sources/FlatBuffers/FlatBufferBuilder.swift
apache-2.0
4
/* * Copyright 2021 Google Inc. 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. */ #if !os(WASI) import Foundation #else import SwiftOverlayShims #endif /// ``FlatBufferBuilder`` builds a `FlatBuffer` through manipulating its internal state. /// /// This is done by creating a ``ByteBuffer`` that hosts the incoming data and /// has a hardcoded growth limit of `2GiB` which is set by the Flatbuffers standards. /// /// ```swift /// var builder = FlatBufferBuilder() /// ``` /// The builder should be always created as a variable, since it would be passed into the writers /// @frozen public struct FlatBufferBuilder { /// Storage for the Vtables used in the buffer are stored in here, so they would be written later in EndTable @usableFromInline internal var _vtableStorage = VTableStorage() /// Flatbuffer data will be written into @usableFromInline internal var _bb: ByteBuffer /// Reference Vtables that were already written to the buffer private var _vtables: [UOffset] = [] /// A check if the buffer is being written into by a different table private var isNested = false /// Dictonary that stores a map of all the strings that were written to the buffer private var stringOffsetMap: [String: Offset] = [:] /// A check to see if finish(::) was ever called to retreive data object private var finished = false /// A check to see if the buffer should serialize Default values private var serializeDefaults: Bool /// Current alignment for the buffer var _minAlignment: Int = 0 { didSet { _bb.alignment = _minAlignment } } /// Gives a read access to the buffer's size public var size: UOffset { _bb.size } #if !os(WASI) /// Data representation of the buffer /// /// Should only be used after ``finish(offset:addPrefix:)`` is called public var data: Data { assert(finished, "Data shouldn't be called before finish()") return Data( bytes: _bb.memory.advanced(by: _bb.writerIndex), count: _bb.capacity &- _bb.writerIndex) } #endif /// Returns the underlying bytes in the ``ByteBuffer`` /// /// Note: This should be used with caution. public var fullSizedByteArray: [UInt8] { let ptr = UnsafeBufferPointer( start: _bb.memory.assumingMemoryBound(to: UInt8.self), count: _bb.capacity) return Array(ptr) } /// Returns the written bytes into the ``ByteBuffer`` /// /// Should only be used after ``finish(offset:addPrefix:)`` is called public var sizedByteArray: [UInt8] { assert(finished, "Data shouldn't be called before finish()") return _bb.underlyingBytes } /// Returns the original ``ByteBuffer`` /// /// Returns the current buffer that was just created /// with the offsets, and data written to it. public var buffer: ByteBuffer { _bb } /// Returns a newly created sized ``ByteBuffer`` /// /// returns a new buffer that is sized to the data written /// to the main buffer public var sizedBuffer: ByteBuffer { assert(finished, "Data shouldn't be called before finish()") return ByteBuffer( memory: _bb.memory.advanced(by: _bb.reader), count: Int(_bb.size)) } // MARK: - Init /// Initialize the buffer with a size /// - Parameters: /// - initialSize: Initial size for the buffer /// - force: Allows default to be serialized into the buffer /// /// This initializes a new builder with an initialSize that would initialize /// a new ``ByteBuffer``. ``FlatBufferBuilder`` by default doesnt serialize defaults /// however the builder can be force by passing true for `serializeDefaults` public init( initialSize: Int32 = 1024, serializeDefaults force: Bool = false) { assert(initialSize > 0, "Size should be greater than zero!") guard isLitteEndian else { fatalError( "Reading/Writing a buffer in big endian machine is not supported on swift") } serializeDefaults = force _bb = ByteBuffer(initialSize: Int(initialSize)) } /// Clears the builder and the buffer from the written data. mutating public func clear() { _minAlignment = 0 isNested = false stringOffsetMap.removeAll(keepingCapacity: true) _vtables.removeAll(keepingCapacity: true) _vtableStorage.clear() _bb.clear() } // MARK: - Create Tables /// Checks if the required fields were serialized into the buffer /// - Parameters: /// - table: offset for the table /// - fields: Array of all the important fields to be serialized /// /// *NOTE: Never call this function, this is only supposed to be called /// by the generated code* @inline(__always) mutating public func require(table: Offset, fields: [Int32]) { for field in fields { let start = _bb.capacity &- Int(table.o) let startTable = start &- Int(_bb.read(def: Int32.self, position: start)) let isOkay = _bb.read( def: VOffset.self, position: startTable &+ Int(field)) != 0 assert(isOkay, "Flatbuffers requires the following field") } } /// Finished the buffer by adding the file id and then calling finish /// - Parameters: /// - offset: Offset of the table /// - fileId: Takes the fileId /// - prefix: if false it wont add the size of the buffer /// /// ``finish(offset:fileId:addPrefix:)`` should be called at the end of creating /// a table /// ```swift /// var root = SomeObject /// .createObject(&builder, /// name: nameOffset) /// builder.finish( /// offset: root, /// fileId: "ax1a", /// addPrefix: true) /// ``` /// File id would append a file id name at the end of the written bytes before, /// finishing the buffer. /// /// Whereas, if `addPrefix` is true, the written bytes would /// include the size of the current buffer. mutating public func finish( offset: Offset, fileId: String, addPrefix prefix: Bool = false) { let size = MemoryLayout<UOffset>.size preAlign( len: size &+ (prefix ? size : 0) &+ FileIdLength, alignment: _minAlignment) assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4") _bb.push(string: fileId, len: 4) finish(offset: offset, addPrefix: prefix) } /// Finished the buffer by adding the file id, offset, and prefix to it. /// - Parameters: /// - offset: Offset of the table /// - prefix: if false it wont add the size of the buffer /// /// ``finish(offset:addPrefix:)`` should be called at the end of creating /// a table /// ```swift /// var root = SomeObject /// .createObject(&builder, /// name: nameOffset) /// builder.finish( /// offset: root, /// addPrefix: true) /// ``` /// If `addPrefix` is true, the written bytes would /// include the size of the current buffer. mutating public func finish( offset: Offset, addPrefix prefix: Bool = false) { notNested() let size = MemoryLayout<UOffset>.size preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment) push(element: refer(to: offset.o)) if prefix { push(element: _bb.size) } _vtableStorage.clear() finished = true } /// ``startTable(with:)`` will let the builder know, that a new object is being serialized. /// /// The function will fatalerror if called while there is another object being serialized. /// ```swift /// let start = Monster /// .startMonster(&fbb) /// ``` /// - Parameter numOfFields: Number of elements to be written to the buffer /// - Returns: Offset of the newly started table @inline(__always) mutating public func startTable(with numOfFields: Int) -> UOffset { notNested() isNested = true _vtableStorage.start(count: numOfFields) return _bb.size } /// ``endTable(at:)`` will let the ``FlatBufferBuilder`` know that the /// object that's written to it is completed /// /// This would be called after all the elements are serialized, /// it will add the current vtable into the ``ByteBuffer``. /// The functions will `fatalError` in case the object is called /// without ``startTable(with:)``, or the object has exceeded the limit of 2GB. /// /// - Parameter startOffset:Start point of the object written /// - returns: The root of the table mutating public func endTable(at startOffset: UOffset) -> UOffset { assert(isNested, "Calling endtable without calling starttable") let sizeofVoffset = MemoryLayout<VOffset>.size let vTableOffset = push(element: SOffset(0)) let tableObjectSize = vTableOffset &- startOffset assert(tableObjectSize < 0x10000, "Buffer can't grow beyond 2 Gigabytes") let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset _bb.fill(padding: _max) _bb.write( value: VOffset(tableObjectSize), index: _bb.writerIndex &+ sizeofVoffset, direct: true) _bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true) var itr = 0 while itr < _vtableStorage.writtenIndex { let loaded = _vtableStorage.load(at: itr) itr = itr &+ _vtableStorage.size guard loaded.offset != 0 else { continue } let _index = (_bb.writerIndex &+ Int(loaded.position)) _bb.write( value: VOffset(vTableOffset &- loaded.offset), index: _index, direct: true) } _vtableStorage.clear() let vt_use = _bb.size var isAlreadyAdded: Int? let vt2 = _bb.memory.advanced(by: _bb.writerIndex) let len2 = vt2.load(fromByteOffset: 0, as: Int16.self) for table in _vtables { let position = _bb.capacity &- Int(table) let vt1 = _bb.memory.advanced(by: position) let len1 = _bb.read(def: Int16.self, position: position) if len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2)) { continue } isAlreadyAdded = Int(table) break } if let offset = isAlreadyAdded { let vTableOff = Int(vTableOffset) let space = _bb.capacity &- vTableOff _bb.write(value: Int32(offset &- vTableOff), index: space, direct: true) _bb.pop(_bb.capacity &- space) } else { _bb.write(value: Int32(vt_use &- vTableOffset), index: Int(vTableOffset)) _vtables.append(_bb.size) } isNested = false return vTableOffset } // MARK: - Builds Buffer /// Asserts to see if the object is not nested @inline(__always) @usableFromInline mutating internal func notNested() { assert(!isNested, "Object serialization must not be nested") } /// Changes the minimuim alignment of the buffer /// - Parameter size: size of the current alignment @inline(__always) @usableFromInline mutating internal func minAlignment(size: Int) { if size > _minAlignment { _minAlignment = size } } /// Gets the padding for the current element /// - Parameters: /// - bufSize: Current size of the buffer + the offset of the object to be written /// - elementSize: Element size @inline(__always) @usableFromInline mutating internal func padding( bufSize: UInt32, elementSize: UInt32) -> UInt32 { ((~bufSize) &+ 1) & (elementSize - 1) } /// Prealigns the buffer before writting a new object into the buffer /// - Parameters: /// - len:Length of the object /// - alignment: Alignment type @inline(__always) @usableFromInline mutating internal func preAlign(len: Int, alignment: Int) { minAlignment(size: alignment) _bb.fill(padding: Int(padding( bufSize: _bb.size &+ UOffset(len), elementSize: UOffset(alignment)))) } /// Prealigns the buffer before writting a new object into the buffer /// - Parameters: /// - len: Length of the object /// - type: Type of the object to be written @inline(__always) @usableFromInline mutating internal func preAlign<T: Scalar>(len: Int, type: T.Type) { preAlign(len: len, alignment: MemoryLayout<T>.size) } /// Refers to an object that's written in the buffer /// - Parameter off: the objects index value @inline(__always) @usableFromInline mutating internal func refer(to off: UOffset) -> UOffset { let size = MemoryLayout<UOffset>.size preAlign(len: size, alignment: size) return _bb.size &- off &+ UInt32(size) } /// Tracks the elements written into the buffer /// - Parameters: /// - offset: The offset of the element witten /// - position: The position of the element @inline(__always) @usableFromInline mutating internal func track(offset: UOffset, at position: VOffset) { _vtableStorage.add(loc: FieldLoc(offset: offset, position: position)) } // MARK: - Inserting Vectors /// ``startVector(_:elementSize:)`` creates a new vector within buffer /// /// The function checks if there is a current object being written, if /// the check passes it creates a buffer alignment of `length * elementSize` /// ```swift /// builder.startVector( /// int32Values.count, elementSize: 4) /// ``` /// /// - Parameters: /// - len: Length of vector to be created /// - elementSize: Size of object type to be written @inline(__always) mutating public func startVector(_ len: Int, elementSize: Int) { notNested() isNested = true preAlign(len: len &* elementSize, type: UOffset.self) preAlign(len: len &* elementSize, alignment: elementSize) } /// ``endVector(len:)`` ends the currently created vector /// /// Calling ``endVector(len:)`` requires the length, of the current /// vector. The length would be pushed to indicate the count of numbers /// within the vector. If ``endVector(len:)`` is called without /// ``startVector(_:elementSize:)`` it asserts. /// /// ```swift /// let vectorOffset = builder. /// endVector(len: int32Values.count) /// ``` /// /// - Parameter len: Length of the buffer /// - Returns: Returns the current ``Offset`` in the ``ByteBuffer`` @inline(__always) mutating public func endVector(len: Int) -> Offset { assert(isNested, "Calling endVector without calling startVector") isNested = false return Offset(offset: push(element: Int32(len))) } /// Creates a vector of type ``Scalar`` into the ``ByteBuffer`` /// /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` /// ```swift /// let vectorOffset = builder. /// createVector([1, 2, 3, 4]) /// ``` /// /// The underlying implementation simply calls ``createVector(_:size:)-4lhrv`` /// /// - Parameter elements: elements to be written into the buffer /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset { createVector(elements, size: elements.count) } /// Creates a vector of type Scalar in the buffer /// /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` /// ```swift /// let vectorOffset = builder. /// createVector([1, 2, 3, 4], size: 4) /// ``` /// /// - Parameter elements: Elements to be written into the buffer /// - Parameter size: Count of elements /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector<T: Scalar>( _ elements: [T], size: Int) -> Offset { let size = size startVector(size, elementSize: MemoryLayout<T>.size) _bb.push(elements: elements) return endVector(len: size) } /// Creates a vector of type ``Enum`` into the ``ByteBuffer`` /// /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` /// ```swift /// let vectorOffset = builder. /// createVector([.swift, .cpp]) /// ``` /// /// The underlying implementation simply calls ``createVector(_:size:)-7cx6z`` /// /// - Parameter elements: elements to be written into the buffer /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset { createVector(elements, size: elements.count) } /// Creates a vector of type ``Enum`` into the ``ByteBuffer`` /// /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` /// ```swift /// let vectorOffset = builder. /// createVector([.swift, .cpp]) /// ``` /// /// - Parameter elements: Elements to be written into the buffer /// - Parameter size: Count of elements /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector<T: Enum>( _ elements: [T], size: Int) -> Offset { let size = size startVector(size, elementSize: T.byteSize) for e in elements.reversed() { _bb.push(value: e.value, len: T.byteSize) } return endVector(len: size) } /// Creates a vector of already written offsets /// /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``. /// /// The underlying implementation simply calls ``createVector(ofOffsets:len:)`` /// /// ```swift /// let namesOffsets = builder. /// createVector(ofOffsets: [name1, name2]) /// ``` /// - Parameter offsets: Array of offsets of type ``Offset`` /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset { createVector(ofOffsets: offsets, len: offsets.count) } /// Creates a vector of already written offsets /// /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into /// ``ByteBuffer``. This is a convenient method instead of calling, /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` /// /// ```swift /// let namesOffsets = builder. /// createVector(ofOffsets: [name1, name2]) /// ``` /// /// - Parameter offsets: Array of offsets of type ``Offset`` /// - Parameter size: Count of elements /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector( ofOffsets offsets: [Offset], len: Int) -> Offset { startVector(len, elementSize: MemoryLayout<Offset>.size) for o in offsets.reversed() { push(element: o) } return endVector(len: len) } /// Creates a vector of strings /// /// ``createVector(ofStrings:)`` creates a vector of `String` into /// ``ByteBuffer``. This is a convenient method instead of manually /// creating the string offsets, you simply pass it to this function /// and it would write the strings into the ``ByteBuffer``. /// After that it calls ``createVector(ofOffsets:)`` /// /// ```swift /// let namesOffsets = builder. /// createVector(ofStrings: ["Name", "surname"]) /// ``` /// /// - Parameter str: Array of string /// - returns: ``Offset`` of the vector @inline(__always) mutating public func createVector(ofStrings str: [String]) -> Offset { var offsets: [Offset] = [] for s in str { offsets.append(create(string: s)) } return createVector(ofOffsets: offsets) } /// Creates a vector of type ``NativeStruct``. /// /// Any swift struct in the generated code, should confirm to /// ``NativeStruct``. Since the generated swift structs are padded /// to the `FlatBuffers` standards. /// /// ```swift /// let offsets = builder. /// createVector(ofStructs: [NativeStr(num: 1), NativeStr(num: 2)]) /// ``` /// /// - Parameter structs: A vector of ``NativeStruct`` /// - Returns: ``Offset`` of the vector @inline(__always) mutating public func createVector<T: NativeStruct>(ofStructs structs: [T]) -> Offset { startVector( structs.count * MemoryLayout<T>.size, elementSize: MemoryLayout<T>.alignment) for i in structs.reversed() { _ = create(struct: i) } return endVector(len: structs.count) } // MARK: - Inserting Structs /// Writes a ``NativeStruct`` into the ``ByteBuffer`` /// /// Adds a native struct that's build and padded according /// to `FlatBuffers` standards. with a predefined position. /// /// ```swift /// let offset = builder.create( /// struct: NativeStr(num: 1), /// position: 10) /// ``` /// /// - Parameters: /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer`` /// - position: The predefined position of the object /// - Returns: ``Offset`` of written struct @inline(__always) @discardableResult mutating public func create<T: NativeStruct>( struct s: T, position: VOffset) -> Offset { let offset = create(struct: s) _vtableStorage.add(loc: FieldLoc( offset: _bb.size, position: VOffset(position))) return offset } /// Writes a ``NativeStruct`` into the ``ByteBuffer`` /// /// Adds a native struct that's build and padded according /// to `FlatBuffers` standards, directly into the buffer without /// a predefined position. /// /// ```swift /// let offset = builder.create( /// struct: NativeStr(num: 1)) /// ``` /// /// - Parameters: /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer`` /// - Returns: ``Offset`` of written struct @inline(__always) @discardableResult mutating public func create<T: NativeStruct>( struct s: T) -> Offset { let size = MemoryLayout<T>.size preAlign(len: size, alignment: MemoryLayout<T>.alignment) _bb.push(struct: s, size: size) return Offset(offset: _bb.size) } // MARK: - Inserting Strings /// Insets a string into the buffer of type `UTF8` /// /// Adds a swift string into ``ByteBuffer`` by encoding it /// using `UTF8` /// /// ```swift /// let nameOffset = builder /// .create(string: "welcome") /// ``` /// /// - Parameter str: String to be serialized /// - returns: ``Offset`` of inserted string @inline(__always) mutating public func create(string str: String?) -> Offset { guard let str = str else { return Offset() } let len = str.utf8.count notNested() preAlign(len: len &+ 1, type: UOffset.self) _bb.fill(padding: 1) _bb.push(string: str, len: len) push(element: UOffset(len)) return Offset(offset: _bb.size) } /// Insets a shared string into the buffer of type `UTF8` /// /// Adds a swift string into ``ByteBuffer`` by encoding it /// using `UTF8`. The function will check if the string, /// is already written to the ``ByteBuffer`` /// /// ```swift /// let nameOffset = builder /// .createShared(string: "welcome") /// /// /// let secondOffset = builder /// .createShared(string: "welcome") /// /// assert(nameOffset.o == secondOffset.o) /// ``` /// /// - Parameter str: String to be serialized /// - returns: ``Offset`` of inserted string @inline(__always) mutating public func createShared(string str: String?) -> Offset { guard let str = str else { return Offset() } if let offset = stringOffsetMap[str] { return offset } let offset = create(string: str) stringOffsetMap[str] = offset return offset } // MARK: - Inseting offsets /// Writes the ``Offset`` of an already written table /// /// Writes the ``Offset`` of a table if not empty into the /// ``ByteBuffer`` /// /// - Parameters: /// - offset: ``Offset`` of another object to be written /// - position: The predefined position of the object @inline(__always) mutating public func add(offset: Offset, at position: VOffset) { if offset.isEmpty { return } add(element: refer(to: offset.o), def: 0, at: position) } /// Pushes a value of type ``Offset`` into the ``ByteBuffer`` /// - Parameter o: ``Offset`` /// - returns: Current position of the ``Offset`` @inline(__always) @discardableResult mutating public func push(element o: Offset) -> UOffset { push(element: refer(to: o.o)) } // MARK: - Inserting Scalars to Buffer /// Writes a ``Scalar`` value into ``ByteBuffer`` /// /// ``add(element:def:at:)`` takes in a default value, and current value /// and the position within the `VTable`. The default value would not /// be serialized if the value is the same as the current value or /// `serializeDefaults` is equal to false. /// /// If serializing defaults is important ``init(initialSize:serializeDefaults:)``, /// passing true for `serializeDefaults` would do the job. /// /// ```swift /// // Adds 10 to the buffer /// builder.add(element: Int(10), def: 1, position 12) /// ``` /// /// *NOTE: Never call this manually* /// /// - Parameters: /// - element: Element to insert /// - def: Default value for that element /// - position: The predefined position of the element @inline(__always) mutating public func add<T: Scalar>( element: T, def: T, at position: VOffset) { if element == def && !serializeDefaults { return } track(offset: push(element: element), at: position) } /// Writes a optional ``Scalar`` value into ``ByteBuffer`` /// /// Takes an optional value to be written into the ``ByteBuffer`` /// /// *NOTE: Never call this manually* /// /// - Parameters: /// - element: Optional element of type scalar /// - position: The predefined position of the element @inline(__always) mutating public func add<T: Scalar>(element: T?, at position: VOffset) { guard let element = element else { return } track(offset: push(element: element), at: position) } /// Pushes a values of type ``Scalar`` into the ``ByteBuffer`` /// /// *NOTE: Never call this manually* /// /// - Parameter element: Element to insert /// - returns: Postion of the Element @inline(__always) @discardableResult mutating public func push<T: Scalar>(element: T) -> UOffset { let size = MemoryLayout<T>.size preAlign( len: size, alignment: size) _bb.push(value: element, len: size) return _bb.size } } extension FlatBufferBuilder: CustomDebugStringConvertible { public var debugDescription: String { """ buffer debug: \(_bb) builder debug: { finished: \(finished), serializeDefaults: \(serializeDefaults), isNested: \(isNested) } """ } /// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer @usableFromInline internal class VTableStorage { /// Memory check since deallocating each time we want to clear would be expensive /// and memory leaks would happen if we dont deallocate the first allocated memory. /// memory is promised to be available before adding `FieldLoc` private var memoryInUse = false /// Size of FieldLoc in memory let size = MemoryLayout<FieldLoc>.stride /// Memeory buffer var memory: UnsafeMutableRawBufferPointer! /// Capacity of the current buffer var capacity: Int = 0 /// Maximuim offset written to the class var maxOffset: VOffset = 0 /// number of fields written into the buffer var numOfFields: Int = 0 /// Last written Index var writtenIndex: Int = 0 /// Creates the memory to store the buffer in @usableFromInline @inline(__always) init() { memory = UnsafeMutableRawBufferPointer.allocate( byteCount: 0, alignment: 0) } @inline(__always) deinit { memory.deallocate() } /// Builds a buffer with byte count of fieldloc.size * count of field numbers /// - Parameter count: number of fields to be written @inline(__always) func start(count: Int) { assert(count >= 0, "number of fields should NOT be negative") let capacity = count &* size ensure(space: capacity) } /// Adds a FieldLoc into the buffer, which would track how many have been written, /// and max offset /// - Parameter loc: Location of encoded element @inline(__always) func add(loc: FieldLoc) { memory.baseAddress?.advanced(by: writtenIndex).storeBytes( of: loc, as: FieldLoc.self) writtenIndex = writtenIndex &+ size numOfFields = numOfFields &+ 1 maxOffset = max(loc.position, maxOffset) } /// Clears the data stored related to the encoded buffer @inline(__always) func clear() { maxOffset = 0 numOfFields = 0 writtenIndex = 0 } /// Ensure that the buffer has enough space instead of recreating the buffer each time. /// - Parameter space: space required for the new vtable @inline(__always) func ensure(space: Int) { guard space &+ writtenIndex > capacity else { return } memory.deallocate() memory = UnsafeMutableRawBufferPointer.allocate( byteCount: space, alignment: size) capacity = space } /// Loads an object of type `FieldLoc` from buffer memory /// - Parameter index: index of element /// - Returns: a FieldLoc at index @inline(__always) func load(at index: Int) -> FieldLoc { memory.load(fromByteOffset: index, as: FieldLoc.self) } } internal struct FieldLoc { var offset: UOffset var position: VOffset } }
2c7613476c477955164c5b36b6374c84
31.615217
111
0.645837
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/IoT1ClickProjects/IoT1ClickProjects_Shapes.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension IoT1ClickProjects { // MARK: Enums // MARK: Shapes public struct AssociateDeviceWithPlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "deviceTemplateName", location: .uri(locationName: "deviceTemplateName")), AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The ID of the physical device to be associated with the given placement in the project. Note that a mandatory 4 character prefix is required for all deviceId values. public let deviceId: String /// The device template name to associate with the device ID. public let deviceTemplateName: String /// The name of the placement in which to associate the device. public let placementName: String /// The name of the project containing the placement in which to associate the device. public let projectName: String public init(deviceId: String, deviceTemplateName: String, placementName: String, projectName: String) { self.deviceId = deviceId self.deviceTemplateName = deviceTemplateName self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.deviceId, name: "deviceId", parent: name, max: 32) try self.validate(self.deviceId, name: "deviceId", parent: name, min: 1) try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, max: 128) try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, min: 1) try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: String, CodingKey { case deviceId } } public struct AssociateDeviceWithPlacementResponse: AWSDecodableShape { public init() {} } public struct CreatePlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// Optional user-defined key/value pairs providing contextual data (such as location or function) for the placement. public let attributes: [String: String]? /// The name of the placement to be created. public let placementName: String /// The name of the project in which to create the placement. public let projectName: String public init(attributes: [String: String]? = nil, placementName: String, projectName: String) { self.attributes = attributes self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.attributes?.forEach { try validate($0.key, name: "attributes.key", parent: name, max: 128) try validate($0.key, name: "attributes.key", parent: name, min: 1) try validate($0.value, name: "attributes[\"\($0.key)\"]", parent: name, max: 800) } try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: String, CodingKey { case attributes case placementName } } public struct CreatePlacementResponse: AWSDecodableShape { public init() {} } public struct CreateProjectRequest: AWSEncodableShape { /// An optional description for the project. public let description: String? /// The schema defining the placement to be created. A placement template defines placement default attributes and device templates. You cannot add or remove device templates after the project has been created. However, you can update callbackOverrides for the device templates using the UpdateProject API. public let placementTemplate: PlacementTemplate? /// The name of the project to create. public let projectName: String /// Optional tags (metadata key/value pairs) to be associated with the project. For example, { {"key1": "value1", "key2": "value2"} }. For more information, see AWS Tagging Strategies. public let tags: [String: String]? public init(description: String? = nil, placementTemplate: PlacementTemplate? = nil, projectName: String, tags: [String: String]? = nil) { self.description = description self.placementTemplate = placementTemplate self.projectName = projectName self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 500) try self.validate(self.description, name: "description", parent: name, min: 0) try self.placementTemplate?.validate(name: "\(name).placementTemplate") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") try self.tags?.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) } } private enum CodingKeys: String, CodingKey { case description case placementTemplate case projectName case tags } } public struct CreateProjectResponse: AWSDecodableShape { public init() {} } public struct DeletePlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The name of the empty placement to delete. public let placementName: String /// The project containing the empty placement to delete. public let projectName: String public init(placementName: String, projectName: String) { self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct DeletePlacementResponse: AWSDecodableShape { public init() {} } public struct DeleteProjectRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The name of the empty project to delete. public let projectName: String public init(projectName: String) { self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct DeleteProjectResponse: AWSDecodableShape { public init() {} } public struct DescribePlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The name of the placement within a project. public let placementName: String /// The project containing the placement to be described. public let projectName: String public init(placementName: String, projectName: String) { self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct DescribePlacementResponse: AWSDecodableShape { /// An object describing the placement. public let placement: PlacementDescription public init(placement: PlacementDescription) { self.placement = placement } private enum CodingKeys: String, CodingKey { case placement } } public struct DescribeProjectRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The name of the project to be described. public let projectName: String public init(projectName: String) { self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct DescribeProjectResponse: AWSDecodableShape { /// An object describing the project. public let project: ProjectDescription public init(project: ProjectDescription) { self.project = project } private enum CodingKeys: String, CodingKey { case project } } public struct DeviceTemplate: AWSEncodableShape & AWSDecodableShape { /// An optional Lambda function to invoke instead of the default Lambda function provided by the placement template. public let callbackOverrides: [String: String]? /// The device type, which currently must be "button". public let deviceType: String? public init(callbackOverrides: [String: String]? = nil, deviceType: String? = nil) { self.callbackOverrides = callbackOverrides self.deviceType = deviceType } public func validate(name: String) throws { try self.callbackOverrides?.forEach { try validate($0.key, name: "callbackOverrides.key", parent: name, max: 128) try validate($0.key, name: "callbackOverrides.key", parent: name, min: 1) try validate($0.value, name: "callbackOverrides[\"\($0.key)\"]", parent: name, max: 200) } try self.validate(self.deviceType, name: "deviceType", parent: name, max: 128) } private enum CodingKeys: String, CodingKey { case callbackOverrides case deviceType } } public struct DisassociateDeviceFromPlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "deviceTemplateName", location: .uri(locationName: "deviceTemplateName")), AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The device ID that should be removed from the placement. public let deviceTemplateName: String /// The name of the placement that the device should be removed from. public let placementName: String /// The name of the project that contains the placement. public let projectName: String public init(deviceTemplateName: String, placementName: String, projectName: String) { self.deviceTemplateName = deviceTemplateName self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, max: 128) try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, min: 1) try self.validate(self.deviceTemplateName, name: "deviceTemplateName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct DisassociateDeviceFromPlacementResponse: AWSDecodableShape { public init() {} } public struct GetDevicesInPlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The name of the placement to get the devices from. public let placementName: String /// The name of the project containing the placement. public let projectName: String public init(placementName: String, projectName: String) { self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct GetDevicesInPlacementResponse: AWSDecodableShape { /// An object containing the devices (zero or more) within the placement. public let devices: [String: String] public init(devices: [String: String]) { self.devices = devices } private enum CodingKeys: String, CodingKey { case devices } } public struct ListPlacementsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The maximum number of results to return per request. If not set, a default value of 100 is used. public let maxResults: Int? /// The token to retrieve the next set of results. public let nextToken: String? /// The project containing the placements to be listed. public let projectName: String public init(maxResults: Int? = nil, nextToken: String? = nil, projectName: String) { self.maxResults = maxResults self.nextToken = nextToken self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 250) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: CodingKey {} } public struct ListPlacementsResponse: AWSDecodableShape { /// The token used to retrieve the next set of results - will be effectively empty if there are no further results. public let nextToken: String? /// An object listing the requested placements. public let placements: [PlacementSummary] public init(nextToken: String? = nil, placements: [PlacementSummary]) { self.nextToken = nextToken self.placements = placements } private enum CodingKeys: String, CodingKey { case nextToken case placements } } public struct ListProjectsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The maximum number of results to return per request. If not set, a default value of 100 is used. public let maxResults: Int? /// The token to retrieve the next set of results. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 250) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListProjectsResponse: AWSDecodableShape { /// The token used to retrieve the next set of results - will be effectively empty if there are no further results. public let nextToken: String? /// An object containing the list of projects. public let projects: [ProjectSummary] public init(nextToken: String? = nil, projects: [ProjectSummary]) { self.nextToken = nextToken self.projects = projects } private enum CodingKeys: String, CodingKey { case nextToken case projects } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// The ARN of the resource whose tags you want to list. public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:iot1click:[A-Za-z0-9_/.-]{0,63}:\\d+:projects/[0-9A-Za-z_-]{1,128}$") } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { /// The tags (metadata key/value pairs) which you have assigned to the resource. public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct PlacementDescription: AWSDecodableShape { /// The user-defined attributes associated with the placement. public let attributes: [String: String] /// The date when the placement was initially created, in UNIX epoch time format. public let createdDate: Date /// The name of the placement. public let placementName: String /// The name of the project containing the placement. public let projectName: String /// The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. public let updatedDate: Date public init(attributes: [String: String], createdDate: Date, placementName: String, projectName: String, updatedDate: Date) { self.attributes = attributes self.createdDate = createdDate self.placementName = placementName self.projectName = projectName self.updatedDate = updatedDate } private enum CodingKeys: String, CodingKey { case attributes case createdDate case placementName case projectName case updatedDate } } public struct PlacementSummary: AWSDecodableShape { /// The date when the placement was originally created, in UNIX epoch time format. public let createdDate: Date /// The name of the placement being summarized. public let placementName: String /// The name of the project containing the placement. public let projectName: String /// The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. public let updatedDate: Date public init(createdDate: Date, placementName: String, projectName: String, updatedDate: Date) { self.createdDate = createdDate self.placementName = placementName self.projectName = projectName self.updatedDate = updatedDate } private enum CodingKeys: String, CodingKey { case createdDate case placementName case projectName case updatedDate } } public struct PlacementTemplate: AWSEncodableShape & AWSDecodableShape { /// The default attributes (key/value pairs) to be applied to all placements using this template. public let defaultAttributes: [String: String]? /// An object specifying the DeviceTemplate for all placements using this (PlacementTemplate) template. public let deviceTemplates: [String: DeviceTemplate]? public init(defaultAttributes: [String: String]? = nil, deviceTemplates: [String: DeviceTemplate]? = nil) { self.defaultAttributes = defaultAttributes self.deviceTemplates = deviceTemplates } public func validate(name: String) throws { try self.defaultAttributes?.forEach { try validate($0.key, name: "defaultAttributes.key", parent: name, max: 128) try validate($0.key, name: "defaultAttributes.key", parent: name, min: 1) try validate($0.value, name: "defaultAttributes[\"\($0.key)\"]", parent: name, max: 800) } try self.deviceTemplates?.forEach { try validate($0.key, name: "deviceTemplates.key", parent: name, max: 128) try validate($0.key, name: "deviceTemplates.key", parent: name, min: 1) try validate($0.key, name: "deviceTemplates.key", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try $0.value.validate(name: "\(name).deviceTemplates[\"\($0.key)\"]") } } private enum CodingKeys: String, CodingKey { case defaultAttributes case deviceTemplates } } public struct ProjectDescription: AWSDecodableShape { /// The ARN of the project. public let arn: String? /// The date when the project was originally created, in UNIX epoch time format. public let createdDate: Date /// The description of the project. public let description: String? /// An object describing the project's placement specifications. public let placementTemplate: PlacementTemplate? /// The name of the project for which to obtain information from. public let projectName: String /// The tags (metadata key/value pairs) associated with the project. public let tags: [String: String]? /// The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. public let updatedDate: Date public init(arn: String? = nil, createdDate: Date, description: String? = nil, placementTemplate: PlacementTemplate? = nil, projectName: String, tags: [String: String]? = nil, updatedDate: Date) { self.arn = arn self.createdDate = createdDate self.description = description self.placementTemplate = placementTemplate self.projectName = projectName self.tags = tags self.updatedDate = updatedDate } private enum CodingKeys: String, CodingKey { case arn case createdDate case description case placementTemplate case projectName case tags case updatedDate } } public struct ProjectSummary: AWSDecodableShape { /// The ARN of the project. public let arn: String? /// The date when the project was originally created, in UNIX epoch time format. public let createdDate: Date /// The name of the project being summarized. public let projectName: String /// The tags (metadata key/value pairs) associated with the project. public let tags: [String: String]? /// The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. public let updatedDate: Date public init(arn: String? = nil, createdDate: Date, projectName: String, tags: [String: String]? = nil, updatedDate: Date) { self.arn = arn self.createdDate = createdDate self.projectName = projectName self.tags = tags self.updatedDate = updatedDate } private enum CodingKeys: String, CodingKey { case arn case createdDate case projectName case tags case updatedDate } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// The ARN of the resouce for which tag(s) should be added or modified. public let resourceArn: String /// The new or modifying tag(s) for the resource. See AWS IoT 1-Click Service Limits for the maximum number of tags allowed per resource. public let tags: [String: String] public init(resourceArn: String, tags: [String: String]) { self.resourceArn = resourceArn self.tags = tags } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:iot1click:[A-Za-z0-9_/.-]{0,63}:\\d+:projects/[0-9A-Za-z_-]{1,128}$") try self.tags.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) } } private enum CodingKeys: String, CodingKey { case tags } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] /// The ARN of the resource whose tag you want to remove. public let resourceArn: String /// The keys of those tags which you want to remove. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:iot1click:[A-Za-z0-9_/.-]{0,63}:\\d+:projects/[0-9A-Za-z_-]{1,128}$") try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) try validate($0, name: "tagKeys[]", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") } try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 50) try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } public struct UpdatePlacementRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "placementName", location: .uri(locationName: "placementName")), AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// The user-defined object of attributes used to update the placement. The maximum number of key/value pairs is 50. public let attributes: [String: String]? /// The name of the placement to update. public let placementName: String /// The name of the project containing the placement to be updated. public let projectName: String public init(attributes: [String: String]? = nil, placementName: String, projectName: String) { self.attributes = attributes self.placementName = placementName self.projectName = projectName } public func validate(name: String) throws { try self.attributes?.forEach { try validate($0.key, name: "attributes.key", parent: name, max: 128) try validate($0.key, name: "attributes.key", parent: name, min: 1) try validate($0.value, name: "attributes[\"\($0.key)\"]", parent: name, max: 800) } try self.validate(self.placementName, name: "placementName", parent: name, max: 128) try self.validate(self.placementName, name: "placementName", parent: name, min: 1) try self.validate(self.placementName, name: "placementName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: String, CodingKey { case attributes } } public struct UpdatePlacementResponse: AWSDecodableShape { public init() {} } public struct UpdateProjectRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "projectName", location: .uri(locationName: "projectName")) ] /// An optional user-defined description for the project. public let description: String? /// An object defining the project update. Once a project has been created, you cannot add device template names to the project. However, for a given placementTemplate, you can update the associated callbackOverrides for the device definition using this API. public let placementTemplate: PlacementTemplate? /// The name of the project to be updated. public let projectName: String public init(description: String? = nil, placementTemplate: PlacementTemplate? = nil, projectName: String) { self.description = description self.placementTemplate = placementTemplate self.projectName = projectName } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 500) try self.validate(self.description, name: "description", parent: name, min: 0) try self.placementTemplate?.validate(name: "\(name).placementTemplate") try self.validate(self.projectName, name: "projectName", parent: name, max: 128) try self.validate(self.projectName, name: "projectName", parent: name, min: 1) try self.validate(self.projectName, name: "projectName", parent: name, pattern: "^[0-9A-Za-z_-]+$") } private enum CodingKeys: String, CodingKey { case description case placementTemplate } } public struct UpdateProjectResponse: AWSDecodableShape { public init() {} } }
947801006e7e4c174302ceae6b088b27
44.949816
314
0.630963
false
false
false
false
felipeflorencio/AdjustViewWhenHitTextField_Swift
refs/heads/master
AdjustViewWhenHitUITextField/ViewController.swift
gpl-2.0
1
// // ViewController.swift // AdjustViewWhenHitUITextField // // Created by Felipe Florencio Garcia on 1/10/16. // Copyright © 2016 Felipe Florencio Garcia. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var likeButton: UIButton! @IBOutlet var txtFirstField: UITextField! @IBOutlet var txtSecondTextField: UITextField! @IBOutlet var btnNext: UIButton! @IBOutlet var scrollView: UIScrollView! @IBOutlet var viewInsideScroll: UIView!; var selectedField:UITextField? override func viewDidLoad() { super.viewDidLoad() // Set observer for receive keyboard notifications NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWasShown(_:)), name:NSNotification.Name(rawValue: "UIKeyboardDidShowNotification"), object:nil) NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWillBeHidden(_:)), name:NSNotification.Name(rawValue: "UIKeyboardWillHideNotification"), object:nil) NotificationCenter.default.addObserver(self, selector:#selector(ViewController.userTappedOnField(_:)), name:NSNotification.Name(rawValue: "UITextFieldTextDidBeginEditingNotification"), object:nil) let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer.init(target:self, action:#selector(ViewController.hideKeyBoard)) viewInsideScroll?.addGestureRecognizer(tapGesture) } deinit { NotificationCenter.default.removeObserver(self) } func hideKeyBoard(){ self.view.endEditing(true) } func userTappedOnField(_ txtSelected: Notification){ if txtSelected.object is UITextField { selectedField = txtSelected.object as? UITextField } } // View readjust actions func keyboardWasShown(_ notification: Notification) { let info:NSDictionary = notification.userInfo! as NSDictionary let keyboardSize:CGSize = ((info.object(forKey: UIKeyboardFrameBeginUserInfoKey) as AnyObject).cgRectValue.size) let txtFieldView:CGPoint = selectedField!.frame.origin; let txtFieldViewHeight:CGFloat = selectedField!.frame.size.height; var visibleRect:CGRect = viewInsideScroll!.frame; visibleRect.size.height -= keyboardSize.height; if !visibleRect.contains(txtFieldView) { let scrollPoint:CGPoint = CGPoint(x: 0.0, y: txtFieldView.y - visibleRect.size.height + (txtFieldViewHeight * 1.5)) scrollView?.setContentOffset(scrollPoint, animated: true) } } func keyboardWillBeHidden(_ notification: Notification) { scrollView?.setContentOffset(CGPoint.zero, animated: true) } }
ba9a01d1e0a6f03f21a9848fc1ebe3b9
33.361446
204
0.696353
false
false
false
false
oddnetworks/odd-sample-apps
refs/heads/master
apple/tvos/tvOSSampleApp/tvOSSampleApp/CollectionInfoViewController.swift
apache-2.0
1
// // CollectionInfoViewController.swift // tvOSSampleApp // // Created by Patrick McConnell on 1/28/16. // Copyright © 2016 Odd Networks. All rights reserved. // import UIKit import OddSDKtvOS class CollectionInfoViewController: UIViewController { @IBOutlet var collectionThumbnailImageView: UIImageView! @IBOutlet var collectionTitleLabel: UILabel! @IBOutlet weak var collectionNotesTextView: UITextView! var collection = OddMediaObjectCollection() { didSet { configureForCollection() } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let id = segue.identifier else { return } switch id { case "videoTableEmbed": guard let vc = segue.destination as? CollectionInfoVideoTableViewController, let node = self.collection.relationshipNodeWithName("entities"), let ids = node.allIds else { break } OddContentStore.sharedStore.objectsOfType(.video, ids: ids, include:nil, callback: { (objects, errors) -> Void in if let videos = objects as? Array<OddVideo> { vc.videos = videos } }) default: break } } // MARK: - Helpers func configureForCollection() { DispatchQueue.main.async { () -> Void in self.collectionTitleLabel?.text = self.collection.title self.collectionNotesTextView?.text = self.collection.notes self.collection.thumbnail { (image) -> Void in if let thumbnail = image { self.collectionThumbnailImageView?.image = thumbnail } } } } }
63fafb8527e83fb9fc50591c1e4a2b13
23.743243
119
0.664664
false
false
false
false
niklassaers/PackStream-Swift
refs/heads/master
Sources/PackStream/String.swift
bsd-3-clause
1
import Foundation extension String: PackProtocol { struct Constants { static let shortStringMinMarker: Byte = 0x80 static let shortStringMaxMarker: Byte = 0x8F static let eightBitByteMarker: Byte = 0xD0 static let sixteenBitByteMarker: Byte = 0xD1 static let thirtytwoBitByteMarker: Byte = 0xD2 } public func pack() throws -> [Byte] { guard let data = self.data(using: .utf8, allowLossyConversion: false) else { throw PackError.notPackable } var bytes = [Byte]() data.withUnsafeBytes { (p: UnsafeRawBufferPointer) -> Void in for byte in p { bytes.append(byte) } } let n = UInt(bytes.count) if n == 0 { return [ 0x80 ] } else if n <= 15 { return try packShortString(bytes) } else if n <= 255 { return try pack8BitString(bytes) } else if n <= 65535 { return try pack16BitString(bytes) } else if n <= 4294967295 as UInt { return try pack32BitString(bytes) } throw PackError.notPackable } private func packShortString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.shortStringMinMarker + UInt8(bytes.count) return [marker] + bytes } private func pack8BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.eightBitByteMarker return [marker, UInt8(bytes.count) ] + bytes } private func pack16BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.sixteenBitByteMarker let size = try UInt16(bytes.count).pack()[0...1] return [marker] + size + bytes } private func pack32BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.thirtytwoBitByteMarker let size = try UInt32(bytes.count).pack()[0...3] return [marker] + size + bytes } public static func unpack(_ bytes: ArraySlice<Byte>) throws -> String { if bytes.count == 0 { return "" } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return try unpackShortString(bytes) case Constants.eightBitByteMarker: return try unpack8BitString(bytes) case Constants.sixteenBitByteMarker: return try unpack16BitString(bytes) case Constants.thirtytwoBitByteMarker: return try unpack32BitString(bytes) default: throw UnpackError.unexpectedByteMarker } } static func markerSizeFor(bytes: ArraySlice<Byte>) throws -> Int { if bytes.count == 0 { return 0 } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return 1 case Constants.eightBitByteMarker: return 2 case Constants.sixteenBitByteMarker: return 3 case Constants.thirtytwoBitByteMarker: return 5 default: throw UnpackError.unexpectedByteMarker } } static func sizeFor(bytes: ArraySlice<Byte>) throws -> Int { if bytes.count == 0 { return 0 } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } let bytes = Array(bytes) switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return Int(firstByte) - Int(Constants.shortStringMinMarker) case Constants.eightBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 2 return Int(try UInt8.unpack(bytes[start..<end])) case Constants.sixteenBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 3 return Int(try UInt16.unpack(bytes[start..<end])) case Constants.thirtytwoBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 5 return Int(try UInt32.unpack(bytes[start..<end])) default: throw UnpackError.unexpectedByteMarker } } private static func unpackShortString(_ bytes: ArraySlice<Byte>) throws -> String { let size = bytes[bytes.startIndex] - Constants.shortStringMinMarker let start = bytes.startIndex + 1 if bytes.count != Int(size) + 1 { let alt = try bytesToString(Array(bytes[start..<bytes.endIndex])) print("Found \(alt)") throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } let end = bytes.endIndex return try bytesToString(Array(bytes[start..<end])) } private static func bytesToString(_ bytes: [Byte]) throws -> String { let data = Data(bytes) guard let string = String(data: data, encoding: .utf8) else { throw UnpackError.incorrectValue } return string } private static func unpack8BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 2 let size = try UInt8.unpack(bytes[start..<end]) if bytes.count != Int(size) + 2 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 2)..<bytes.endIndex])) } private static func unpack16BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 3 let size = try UInt16.unpack(bytes[start..<end]) if bytes.count != Int(size) + 3 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 3)..<bytes.endIndex])) } private static func unpack32BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 5 let size = try UInt32.unpack(bytes[start..<end]) if bytes.count != Int(size) + 5 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 5)..<bytes.endIndex])) } }
d76f6aff551e8cb01b3641c8310e698b
28.812227
87
0.589424
false
false
false
false
kckd/ClassicAppExporter
refs/heads/master
classicexp-mac/ClassicListExporter/ListNameViewController.swift
unlicense
1
// // ListNameViewController.swift // ClassicListExporter // // Created by Casey Cady on 2/3/17. // Copyright © 2017 Casey Cady. All rights reserved. // import Cocoa class ListNameViewController: NSViewController { @IBOutlet weak var listNameTextField: NSTextField! public var list: List? public var caches: [String]? override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } override func viewWillAppear() { caches = DatabaseManager.defaultMgr?.getCaches(forList: list!.id!) listNameTextField.stringValue = list!.name! } @IBAction func onOkay(_ sender: Any) { let waitStr = "Please wait. Exporting list." let alert = NSAlert() alert.informativeText = waitStr alert.alertStyle = .informational alert.addButton(withTitle: "Cancel") alert.buttons[0].isHidden = true; alert.beginSheetModal(for: view.window!, completionHandler: { (_) in return }) let task = CreateListAPITask(name: listNameTextField.stringValue) task.execute { (json) in if let code = json["referenceCode"].string { let addTask = AddToListAPITask(listCode: code, cacheCodes: self.caches!) addTask.execute { (result) in DispatchQueue.main.async { alert.buttons[0].performClick(alert) let waitStr = "List Exported" let alert = NSAlert() alert.informativeText = waitStr alert.alertStyle = .informational alert.addButton(withTitle: "Okay") alert.beginSheetModal(for: self.view.window!, completionHandler: { (_) in DispatchQueue.main.async { self.dismiss(nil) } return }) } } } } } @IBAction func onCancel(_ sender: Any) { dismiss(nil) } }
059f3218d2232a263e7faa49c755fa65
32.430769
97
0.528302
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/530-relops-1.swift
apache-2.0
4
// Test relational operators on integers import assert; (int r) f () { r = 1; } main { // Delayed computation assert(f() == 1, "delayed == 1"); assert(!(f() == 0), "delayed == 0"); assert(f() != 0, "delayed != 0"); assert(!(f() != 1), "delayed != 1"); assert(f() > -1, "delayed > -1"); assert(f() <= 23, "delayed <= 23"); assert(!(f() < 1), "delayed < 1"); assert(f() >= 0, "delayed >= 0"); // Immediate (to check constant folding) int a = 1; assert(a == 1, "immediate == 1"); assert(!(a == 0), "immediate == 0"); assert(a != 0, "immediate != 0"); assert(!(a != 1), "immediate != 1"); assert(a > -1, "immediate > -1"); assert(a <= 23, "immediate <= 23"); assert(!(a < 1), "immediate < 1"); assert(a >= 0, "immediate >= 0"); }
7a976858a26dadbb246cc5eea86bb057
26
44
0.476543
false
false
false
false
CartoDB/mobile-ios-samples
refs/heads/master
AdvancedMap.Swift/Feature Demo/NavigationStartButton.swift
bsd-2-clause
1
// // NavigationStartButton.swift // AdvancedMap.Swift // // Created by Aare Undo on 15/11/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation class NavigationStartButton: PopupButton { var delegate: SwitchDelegate? let label = UILabel() var isStopped: Bool { get { return label.text == startText } } var isPaused: Bool { get { return label.text == resumeText } } convenience init() { self.init(frame: CGRect.zero) initialize(imageUrl: "onImageUrl") label.textColor = UIColor.white label.font = UIFont(name: "HelveticaNeue", size: 10) label.textAlignment = .center label.clipsToBounds = true addSubview(label) let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.switchChanged(_:))) addGestureRecognizer(recognizer) toggle() } override func layoutSubviews() { super.layoutSubviews() label.frame = bounds } @objc func switchChanged(_ sender: UITapGestureRecognizer) { delegate?.switchChanged() toggle() } let startText = "START" let stopText = "STOP" let resumeText = "RESUME" func toggle() { if (isStopped || isPaused) { label.text = stopText backgroundColor = Colors.locationRed } else { label.text = startText backgroundColor = Colors.green } } func pause() { label.text = resumeText backgroundColor = Colors.softOrange } }
97e2caa432413e536f3e6597dd1007af
20.4375
104
0.559184
false
false
false
false
Sherlouk/IGListKit
refs/heads/master
Carthage/Checkouts/IGListKit/Examples/Examples-tvOS/IGListKitExamples/SectionControllers/HorizontalSectionController.swift
bsd-3-clause
4
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit final class HorizontalSectionController: IGListSectionController, IGListSectionType, IGListAdapterDataSource { var number: Int? lazy var adapter: IGListAdapter = { let adapter = IGListAdapter(updater: IGListAdapterUpdater(), viewController: self.viewController, workingRangeSize: 0) adapter.dataSource = self return adapter }() override init() { super.init() self.inset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) } func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 340) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(of: EmbeddedCollectionViewCell.self, for: self, at: index) as! EmbeddedCollectionViewCell adapter.collectionView = cell.collectionView return cell } func didUpdate(to object: Any) { number = object as? Int } func didSelectItem(at index: Int) {} // MARK: IGListAdapterDataSource func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { guard let number = number else { return [] } return (0..<number).map { $0 as IGListDiffable } } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { return CarouselSectionController() } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } }
3a257911b0c77bcb19f84253441461ea
34.132353
147
0.672248
false
false
false
false
3ph/SplitSlider
refs/heads/develop
Example/Pods/Nimble/Sources/Nimble/DSL+Wait.swift
mit
17
import Dispatch import Foundation private enum ErrorResult { case exception(NSException) case error(Error) case none } /// Only classes, protocols, methods, properties, and subscript declarations can be /// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style /// asynchronous waiting logic so that it may be called from Objective-C and Swift. internal class NMBWait: NSObject { // About these kind of lines, `@objc` attributes are only required for Objective-C // support, so that should be conditional on Darwin platforms and normal Xcode builds // (non-SwiftPM builds). #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE @objc internal class func until( timeout: TimeInterval, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) { return throwableUntil(timeout: timeout, file: file, line: line) { done in action(done) } } #else internal class func until( timeout: TimeInterval, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) { return throwableUntil(timeout: timeout, file: file, line: line) { done in action(done) } } #endif // Using a throwable closure makes this method not objc compatible. internal class func throwableUntil( timeout: TimeInterval, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) throws -> Void) { let awaiter = NimbleEnvironment.activeInstance.awaiter let leeway = timeout / 2.0 // swiftlint:disable:next line_length let result = awaiter.performBlock(file: file, line: line) { (done: @escaping (ErrorResult) -> Void) throws -> Void in DispatchQueue.main.async { let capture = NMBExceptionCapture( handler: ({ exception in done(.exception(exception)) }), finally: ({ }) ) capture.tryBlock { do { try action { done(.none) } } catch let e { done(.error(e)) } } } }.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line) switch result { case .incomplete: internalError("Reached .incomplete state for waitUntil(...).") case .blockedRunLoop: fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway), file: file, line: line) case .timedOut: let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) case let .raisedException(exception): fail("Unexpected exception raised: \(exception)") case let .errorThrown(error): fail("Unexpected error thrown: \(error)") case .completed(.exception(let exception)): fail("Unexpected exception raised: \(exception)") case .completed(.error(let error)): fail("Unexpected error thrown: \(error)") case .completed(.none): // success break } } #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE @objc(untilFile:line:action:) internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) { until(timeout: 1, file: file, line: line, action: action) } #else internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) { until(timeout: 1, file: file, line: line, action: action) } #endif } internal func blockedRunLoopErrorMessageFor(_ fnName: String, leeway: TimeInterval) -> String { // swiftlint:disable:next line_length return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." } /// Wait asynchronously until the done closure is called or the timeout has been reached. /// /// @discussion /// Call the done() closure to indicate the waiting has completed. /// /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func waitUntil(timeout: TimeInterval = AsyncDefaults.Timeout, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) { NMBWait.until(timeout: timeout, file: file, line: line, action: action) }
595cac64c16130140cddb640bcfefc49
44.551724
381
0.589894
false
false
false
false
SamirTalwar/advent-of-code
refs/heads/main
2018/AOC_23_2.swift
mit
1
let inputParser = try! RegExp(pattern: "^pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, r=(\\d+)$") let me = Position(x: 0, y: 0, z: 0) struct Position: Hashable, CustomStringConvertible { let x: Int let y: Int let z: Int var description: String { return "(\(x), \(y), \(z))" } func distance(from other: Position) -> Int { return abs(x - other.x) + abs(y - other.y) + abs(z - other.z) } } struct Cube: Hashable { let center: Position let radius: Int func overlaps(with other: Cube) -> Bool { return other.center.distance(from: center) <= radius + other.radius } } struct Graph<T>: CustomStringConvertible where T: Hashable { private var edges: [T: Set<T>] init() { edges = [:] } var description: String { return edges.flatMap { a, bs in bs.map { b in "\(a) -> \(b)" } }.joined(separator: "\n") } mutating func addEdge(between a: T, and b: T) { if edges[a] == nil { edges[a] = [] } if edges[b] == nil { edges[b] = [] } edges[a]!.insert(b) edges[b]!.insert(a) } func maximalCliques() -> Set<Set<T>> { return bronKerbosch(r: [], p: Set(edges.keys), x: []) } private func bronKerbosch(r: Set<T>, p immutableP: Set<T>, x immutableX: Set<T>) -> Set<Set<T>> { var p = immutableP var x = immutableX if p.isEmpty, x.isEmpty { return [r] } let u = p.union(x).max(by: comparing { v in self.edges[v]!.count })! var rs: Set<Set<T>> = [] for v in p.subtracting(edges[u]!) { rs.formUnion(bronKerbosch(r: r.union([v]), p: p.intersection(edges[v]!), x: x.intersection(edges[v]!))) p.remove(v) x.insert(v) } return rs } } func main() { let nanobots = StdIn().map(parseInput) var graph: Graph<Cube> = Graph() for a in nanobots { for b in nanobots { if a.center == b.center { continue } if a.overlaps(with: b) { graph.addEdge(between: a, and: b) } } } let cliques = graph.maximalCliques() let bestSize = cliques.map { clique in clique.count }.max() let bestCliques = cliques.filter { clique in clique.count == bestSize } if bestCliques.count != 1 { fatalError("Got \(bestCliques.count) cliques.") } let clique = bestCliques.first! let bestDistance = clique.map { bot in bot.center.distance(from: me) - bot.radius }.max()! print(bestDistance) } func parseInput(input: String) -> Cube { guard let match = inputParser.firstMatch(in: input) else { fatalError("Could not parse \"\(input)\".") } return Cube( center: Position( x: Int(match[1])!, y: Int(match[2])!, z: Int(match[3])! ), radius: Int(match[4])! ) }
d182b53bcf51042b8d45662e60136b5a
26.588785
115
0.524051
false
false
false
false
fuzza/functional-swift-examples
refs/heads/master
functional-swift-playground.playground/Pages/binary-search-tree.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation extension Sequence { func all(_ predicate: (Iterator.Element) -> Bool) -> Bool { for x in self where !predicate(x) { return false } return true } } indirect enum BinarySearchTree <Element: Comparable> { case Leaf case Node (BinarySearchTree<Element>, Element, BinarySearchTree<Element>) } let leaf = BinarySearchTree<Int>.Leaf let node = BinarySearchTree<Int>.Node(leaf, 5, leaf) extension BinarySearchTree { init() { self = .Leaf } init(value: Element) { self = .Node(.Leaf, value, .Leaf) } } extension BinarySearchTree { var count: Int { switch self { case .Leaf: return 0 case let .Node(left, _, right): return 1 + left.count + right.count } } } extension BinarySearchTree { var elements: [Element] { switch self { case .Leaf: return [] case let .Node(left, x, right): return left.elements + [x] + right.elements } } } extension BinarySearchTree { var isEmpty: Bool { if case .Leaf = self { return true } return false } } extension BinarySearchTree { var isBST: Bool { switch self { case .Leaf: return true case let .Node(left, x, right): return left.elements.all { $0 < x } && right.elements.all { $0 > x} && left.isBST && right.isBST } } } extension BinarySearchTree { func contains(_ value: Element) -> Bool { switch self { case .Leaf: return false case let .Node(_, x, _) where value == x: return true case let .Node(left, x, _) where value < x: return left.contains(value) case let .Node(_, x, right) where value > x: return right.contains(value) default: fatalError("Should not happen") } } } extension BinarySearchTree { mutating func insert(_ value: Element) { switch self { case .Leaf: self = BinarySearchTree(value: value) case let .Node(left, x, right): var mutableLeft = left var mutableRight = right if(value < x) { mutableLeft.insert(value) } if(value > x) { mutableRight.insert(value) } self = .Node(mutableLeft, x, mutableRight) } } } let tree = BinarySearchTree(value:0) var mutableTree = tree mutableTree.insert(10) mutableTree.insert(8) print(tree.elements) print(mutableTree.elements) //: [Next](@next)
27cd2ed1d287546f148e7833c0fb6d59
21.838983
77
0.54731
false
false
false
false
yannickl/AwaitKit
refs/heads/master
Tests/AwaitKitTests/AwaitKitAsyncTests.swift
mit
1
/* * AwaitKit * * Copyright 2016-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import AwaitKit import PromiseKit import XCTest class AwaitKitAsyncTests: XCTestCase { let commonError = NSError(domain: "com.yannickloriot.error", code: 320, userInfo: nil) func testSimpleDelayedValidAsyncBlock() { let expect = expectation(description: "Async should return value") let promise: Promise<String> = async { Thread.sleep(forTimeInterval: 0.2) return "AwaitedPromiseKit" } _ = promise.then { value -> Promise<Void> in expect.fulfill() return Promise() } waitForExpectations(timeout: 0.5) { error in if error == nil { XCTAssertEqual(promise.value, "AwaitedPromiseKit") } } } func testSimpleFailedAsyncBlock() { let expect = expectation(description: "Async should not return value") let promise: Promise<String> = async { throw self.commonError } _ = promise.catch { err in expect.fulfill() } waitForExpectations(timeout: 0.1) { error in if error == nil { XCTAssertNil(promise.value) } } } func testNoReturnedValueAsyncBlock() { let expect1 = expectation(description: "Async should not return value") let expect2 = expectation(description: "Async should throw") async { expect1.fulfill() } async { defer { expect2.fulfill() } throw self.commonError } waitForExpectations(timeout: 0.1, handler: nil) } }
996119762cc2812b6d05111cad3c3977
27.336957
88
0.694668
false
true
false
false
groue/GRDB.swift
refs/heads/master
Tests/GRDBTests/PrimaryKeyInfoTests.swift
mit
1
import XCTest @testable import GRDB class PrimaryKeyInfoTests: GRDBTestCase { func testMissingTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { _ = try db.primaryKey("items") XCTFail("Expected Error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, "no such table: items") XCTAssertEqual(error.description, "SQLite error 1: no such table: items") } } } func testView() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE VIEW items AS SELECT 1") do { _ = try db.primaryKey("items") XCTFail("Expected Error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, "no such table: items") XCTAssertEqual(error.description, "SQLite error 1: no such table: items") } } } func testHiddenRowID() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT)") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, [Column.rowID.name]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertTrue(primaryKey.isRowID) XCTAssertTrue(primaryKey.tableHasRowID) } } func testIntegerPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, ["id"]) XCTAssertEqual(primaryKey.rowIDColumn, "id") XCTAssertTrue(primaryKey.isRowID) XCTAssertTrue(primaryKey.tableHasRowID) } } func testNonRowIDPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY)") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, ["name"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) XCTAssertTrue(primaryKey.tableHasRowID) } } func testCompoundPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b))") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, ["a", "b"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) XCTAssertTrue(primaryKey.tableHasRowID) } } func testNonRowIDPrimaryKeyWithoutRowID() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY) WITHOUT ROWID") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, ["name"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) XCTAssertFalse(primaryKey.tableHasRowID) } } func testCompoundPrimaryKeyWithoutRowID() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b)) WITHOUT ROWID") let primaryKey = try db.primaryKey("items") XCTAssertEqual(primaryKey.columns, ["a", "b"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) XCTAssertFalse(primaryKey.tableHasRowID) } } }
e71f97eae62451da4e91c85ecb4951a2
38.933962
106
0.604063
false
true
false
false
nslogo/DouYuZB
refs/heads/master
DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift
mit
1
// // NetworkTools.swift // Alamofire的测试 // // Created by 1 on 16/9/19. // Copyright © 2016年 小码哥. All rights reserved. // //import UIKit //import Alamofire // //enum MethodType { // case GET // case POST //} // //class NetworkTools { // class func requestData(type : MethodType, URLString : String, parameters : [String : NSString]? = nil, finishedCallback : @escaping (_ result : AnyObject) -> ()) { // // // 1.获取类型 // let method = type == .GET ? Method.GET : Method.POST // // 2.发送网络请求 // Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) in // // 3.获取结果 // guard let result = response.result.value else { // print(response.result.error) // return // } // // 4.将结果回调出去 // finishedCallback(result: result) // } // } //}
04c53174d531402444282c653b5d9a58
26.363636
169
0.548173
false
false
false
false
CreazyShadow/SimpleDemo
refs/heads/master
DemoClass/RxSwiftProject/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift
apache-2.0
11
// // DelegateProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) import RxSwift #if SWIFT_PACKAGE && !os(Linux) import RxCocoaRuntime #endif /// Base class for `DelegateProxyType` protocol. /// /// This implementation is not thread safe and can be used only from one thread (Main thread). open class DelegateProxy<P: AnyObject, D>: _RXDelegateProxy { public typealias ParentObject = P public typealias Delegate = D private var _sentMessageForSelector = [Selector: MessageDispatcher]() private var _methodInvokedForSelector = [Selector: MessageDispatcher]() /// Parent object associated with delegate proxy. private weak private(set) var _parentObject: ParentObject? fileprivate let _currentDelegateFor: (ParentObject) -> AnyObject? fileprivate let _setCurrentDelegateTo: (AnyObject?, ParentObject) -> () /// Initializes new instance. /// /// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object. public init<Proxy: DelegateProxyType>(parentObject: ParentObject, delegateProxy: Proxy.Type) where Proxy: DelegateProxy<ParentObject, Delegate>, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate { self._parentObject = parentObject self._currentDelegateFor = delegateProxy._currentDelegate self._setCurrentDelegateTo = delegateProxy._setCurrentDelegate MainScheduler.ensureExecutingOnScheduler() #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif super.init() } /** Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*. Only methods that have `void` return value can be observed using this method because those methods are used as a notification mechanism. It doesn't matter if they are optional or not. Observing is performed by installing a hidden associated `PublishSubject` that is used to dispatch messages to observers. Delegate methods that have non `void` return value can't be observed directly using this method because: * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism * there is no sensible automatic way to determine a default return value In case observing of delegate methods that have return type is required, it can be done by manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. e.g. // delegate proxy part (RxScrollViewDelegateProxy) let internalSubject = PublishSubject<CGPoint> public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { internalSubject.on(.next(arg1)) return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue } .... // reactive property implementation in a real class (`UIScrollView`) public var property: Observable<CGPoint> { let proxy = RxScrollViewDelegateProxy.proxy(for: base) return proxy.internalSubject.asObservable() } **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.", that means that manual observing method is required analog to the example above because delegate method has already been implemented.** - parameter selector: Selector used to filter observed invocations of delegate methods. - returns: Observable sequence of arguments passed to `selector` method. */ open func sentMessage(_ selector: Selector) -> Observable<[Any]> { MainScheduler.ensureExecutingOnScheduler() let subject = _sentMessageForSelector[selector] if let subject = subject { return subject.asObservable() } else { let subject = MessageDispatcher(selector: selector, delegateProxy: self) _sentMessageForSelector[selector] = subject return subject.asObservable() } } /** Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*. Only methods that have `void` return value can be observed using this method because those methods are used as a notification mechanism. It doesn't matter if they are optional or not. Observing is performed by installing a hidden associated `PublishSubject` that is used to dispatch messages to observers. Delegate methods that have non `void` return value can't be observed directly using this method because: * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism * there is no sensible automatic way to determine a default return value In case observing of delegate methods that have return type is required, it can be done by manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. e.g. // delegate proxy part (RxScrollViewDelegateProxy) let internalSubject = PublishSubject<CGPoint> public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { internalSubject.on(.next(arg1)) return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue } .... // reactive property implementation in a real class (`UIScrollView`) public var property: Observable<CGPoint> { let proxy = RxScrollViewDelegateProxy.proxy(for: base) return proxy.internalSubject.asObservable() } **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.", that means that manual observing method is required analog to the example above because delegate method has already been implemented.** - parameter selector: Selector used to filter observed invocations of delegate methods. - returns: Observable sequence of arguments passed to `selector` method. */ open func methodInvoked(_ selector: Selector) -> Observable<[Any]> { MainScheduler.ensureExecutingOnScheduler() let subject = _methodInvokedForSelector[selector] if let subject = subject { return subject.asObservable() } else { let subject = MessageDispatcher(selector: selector, delegateProxy: self) _methodInvokedForSelector[selector] = subject return subject.asObservable() } } fileprivate func checkSelectorIsObservable(_ selector: Selector) { MainScheduler.ensureExecutingOnScheduler() if hasWiredImplementation(for: selector) { print("⚠️ Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.") return } if voidDelegateMethodsContain(selector) { return } // In case `_forwardToDelegate` is `nil`, it is assumed the check is being done prematurely. if !(self._forwardToDelegate?.responds(to: selector) ?? true) { print("⚠️ Using delegate proxy dynamic interception method but the target delegate object doesn't respond to the requested selector. " + "In case pure Swift delegate proxy is being used please use manual observing method by using`PublishSubject`s. " + " (selector: `\(selector)`, forwardToDelegate: `\(_forwardToDelegate ?? self)`)") } } // proxy open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) { _sentMessageForSelector[selector]?.on(.next(arguments)) } open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) { _methodInvokedForSelector[selector]?.on(.next(arguments)) } /// Returns reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - returns: Value of reference if set or nil. open func forwardToDelegate() -> Delegate? { return castOptionalOrFatalError(self._forwardToDelegate) } /// Sets reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. open func setForwardToDelegate(_ delegate: Delegate?, retainDelegate: Bool) { #if DEBUG // 4.0 all configurations MainScheduler.ensureExecutingOnScheduler() #endif self._setForwardToDelegate(delegate, retainDelegate: retainDelegate) let sentSelectors: [Selector] = self._sentMessageForSelector.values.filter { $0.hasObservers }.map { $0.selector } let invokedSelectors: [Selector] = self._methodInvokedForSelector.values.filter { $0.hasObservers }.map { $0.selector } let allUsedSelectors = sentSelectors + invokedSelectors for selector in Set(allUsedSelectors) { checkSelectorIsObservable(selector) } self.reset() } private func hasObservers(selector: Selector) -> Bool { return (_sentMessageForSelector[selector]?.hasObservers ?? false) || (_methodInvokedForSelector[selector]?.hasObservers ?? false) } override open func responds(to aSelector: Selector!) -> Bool { return super.responds(to: aSelector) || (self._forwardToDelegate?.responds(to: aSelector) ?? false) || (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector)) } fileprivate func reset() { guard let parentObject = self._parentObject else { return } let maybeCurrentDelegate = _currentDelegateFor(parentObject) if maybeCurrentDelegate === self { _setCurrentDelegateTo(nil, parentObject) _setCurrentDelegateTo(castOrFatalError(self), parentObject) } } deinit { for v in _sentMessageForSelector.values { v.on(.completed) } for v in _methodInvokedForSelector.values { v.on(.completed) } #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } fileprivate let mainScheduler = MainScheduler() fileprivate final class MessageDispatcher { private let dispatcher: PublishSubject<[Any]> private let result: Observable<[Any]> fileprivate let selector: Selector init<P, D>(selector: Selector, delegateProxy _delegateProxy: DelegateProxy<P, D>) { weak var weakDelegateProxy = _delegateProxy let dispatcher = PublishSubject<[Any]>() self.dispatcher = dispatcher self.selector = selector self.result = dispatcher .do(onSubscribed: { weakDelegateProxy?.checkSelectorIsObservable(selector); weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() }) .share() .subscribeOn(mainScheduler) } var on: (Event<[Any]>) -> () { return self.dispatcher.on } var hasObservers: Bool { return self.dispatcher.hasObservers } func asObservable() -> Observable<[Any]> { return self.result } } #endif
50a82b21003d0018f0e8729706c63161
41.665529
164
0.635469
false
false
false
false
Shopify/mobile-buy-sdk-ios
refs/heads/main
Buy/Generated/Storefront/ManualDiscountApplication.swift
mit
1
// // ManualDiscountApplication.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // 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 extension Storefront { /// Manual discount applications capture the intentions of a discount that was /// manually created. open class ManualDiscountApplicationQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = ManualDiscountApplication /// The method by which the discount's value is allocated to its entitled /// items. @discardableResult open func allocationMethod(alias: String? = nil) -> ManualDiscountApplicationQuery { addField(field: "allocationMethod", aliasSuffix: alias) return self } /// The description of the application. @discardableResult open func description(alias: String? = nil) -> ManualDiscountApplicationQuery { addField(field: "description", aliasSuffix: alias) return self } /// Which lines of targetType that the discount is allocated over. @discardableResult open func targetSelection(alias: String? = nil) -> ManualDiscountApplicationQuery { addField(field: "targetSelection", aliasSuffix: alias) return self } /// The type of line that the discount is applicable towards. @discardableResult open func targetType(alias: String? = nil) -> ManualDiscountApplicationQuery { addField(field: "targetType", aliasSuffix: alias) return self } /// The title of the application. @discardableResult open func title(alias: String? = nil) -> ManualDiscountApplicationQuery { addField(field: "title", aliasSuffix: alias) return self } /// The value of the discount application. @discardableResult open func value(alias: String? = nil, _ subfields: (PricingValueQuery) -> Void) -> ManualDiscountApplicationQuery { let subquery = PricingValueQuery() subfields(subquery) addField(field: "value", aliasSuffix: alias, subfields: subquery) return self } } /// Manual discount applications capture the intentions of a discount that was /// manually created. open class ManualDiscountApplication: GraphQL.AbstractResponse, GraphQLObject, DiscountApplication { public typealias Query = ManualDiscountApplicationQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "allocationMethod": guard let value = value as? String else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return DiscountApplicationAllocationMethod(rawValue: value) ?? .unknownValue case "description": if value is NSNull { return nil } guard let value = value as? String else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return value case "targetSelection": guard let value = value as? String else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return DiscountApplicationTargetSelection(rawValue: value) ?? .unknownValue case "targetType": guard let value = value as? String else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return DiscountApplicationTargetType(rawValue: value) ?? .unknownValue case "title": guard let value = value as? String else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return value case "value": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } return try UnknownPricingValue.create(fields: value) default: throw SchemaViolationError(type: ManualDiscountApplication.self, field: fieldName, value: fieldValue) } } /// The method by which the discount's value is allocated to its entitled /// items. open var allocationMethod: Storefront.DiscountApplicationAllocationMethod { return internalGetAllocationMethod() } func internalGetAllocationMethod(alias: String? = nil) -> Storefront.DiscountApplicationAllocationMethod { return field(field: "allocationMethod", aliasSuffix: alias) as! Storefront.DiscountApplicationAllocationMethod } /// The description of the application. open var description: String? { return internalGetDescription() } func internalGetDescription(alias: String? = nil) -> String? { return field(field: "description", aliasSuffix: alias) as! String? } /// Which lines of targetType that the discount is allocated over. open var targetSelection: Storefront.DiscountApplicationTargetSelection { return internalGetTargetSelection() } func internalGetTargetSelection(alias: String? = nil) -> Storefront.DiscountApplicationTargetSelection { return field(field: "targetSelection", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetSelection } /// The type of line that the discount is applicable towards. open var targetType: Storefront.DiscountApplicationTargetType { return internalGetTargetType() } func internalGetTargetType(alias: String? = nil) -> Storefront.DiscountApplicationTargetType { return field(field: "targetType", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetType } /// The title of the application. open var title: String { return internalGetTitle() } func internalGetTitle(alias: String? = nil) -> String { return field(field: "title", aliasSuffix: alias) as! String } /// The value of the discount application. open var value: PricingValue { return internalGetValue() } func internalGetValue(alias: String? = nil) -> PricingValue { return field(field: "value", aliasSuffix: alias) as! PricingValue } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { return [] } } }
253e5bb66827ea1f17b07575bdfd5b4c
36.26178
117
0.743291
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePaymentSheet/StripePaymentSheet/PaymentSheet/Elements/CardSectionWithScanner/CardSectionWithScannerView.swift
mit
1
// // CardSectionWithScannerView.swift // StripePaymentSheet // // Created by Yuki Tokuhiro on 3/22/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Foundation import UIKit @_spi(STP) import StripeUICore @_spi(STP) import StripeCore @_spi(STP) import StripePayments @_spi(STP) import StripePaymentsUI /** A view that wraps a normal section and adds a "Scan card" button. Tapping the button displays a card scan view below the section. */ /// For internal SDK use only @objc(STP_Internal_CardSectionWithScannerView) @available(iOS 13, macCatalyst 14, *) final class CardSectionWithScannerView: UIView { let cardSectionView: UIView lazy var cardScanButton: UIButton = { let button = UIButton.makeCardScanButton(theme: theme) button.addTarget(self, action: #selector(didTapCardScanButton), for: .touchUpInside) return button }() lazy var cardScanningView: CardScanningView = { let scanningView = CardScanningView() scanningView.alpha = 0 scanningView.isHidden = true scanningView.delegate = self return scanningView }() weak var delegate: CardSectionWithScannerViewDelegate? private let theme: ElementsUITheme init(cardSectionView: UIView, delegate: CardSectionWithScannerViewDelegate, theme: ElementsUITheme = .default) { self.cardSectionView = cardSectionView self.delegate = delegate self.theme = theme super.init(frame: .zero) installConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func installConstraints() { let sectionTitle = ElementsUI.makeSectionTitleLabel(theme: theme) sectionTitle.text = String.Localized.card_information let cardSectionTitleAndButton = UIStackView(arrangedSubviews: [sectionTitle, cardScanButton]) let stack = UIStackView(arrangedSubviews: [cardSectionTitleAndButton, cardSectionView, cardScanningView]) stack.axis = .vertical stack.spacing = ElementsUI.sectionSpacing stack.setCustomSpacing(ElementsUI.formSpacing, after: cardSectionView) addAndPinSubview(stack) } @available(iOS 13, macCatalyst 14, *) @objc func didTapCardScanButton() { setCardScanVisible(true) cardScanningView.start() becomeFirstResponder() } private func setCardScanVisible(_ isCardScanVisible: Bool) { UIView.animate(withDuration: PaymentSheetUI.defaultAnimationDuration) { self.cardScanButton.alpha = isCardScanVisible ? 0 : 1 self.cardScanningView.isHidden = !isCardScanVisible self.cardScanningView.alpha = isCardScanVisible ? 1 : 0 } } override var canBecomeFirstResponder: Bool { return true } override func resignFirstResponder() -> Bool { cardScanningView.stop() return super.resignFirstResponder() } } @available(iOS 13, macCatalyst 14, *) extension CardSectionWithScannerView: STP_Internal_CardScanningViewDelegate { func cardScanningView(_ cardScanningView: CardScanningView, didFinishWith cardParams: STPPaymentMethodCardParams?) { setCardScanVisible(false) if let cardParams = cardParams { self.delegate?.didScanCard(cardParams: cardParams) } } } // MARK: - CardFormElementViewDelegate protocol CardSectionWithScannerViewDelegate: AnyObject { func didScanCard(cardParams: STPPaymentMethodCardParams) }
b6b7a78c10452b7d59f21603aeca7cd7
34.909091
130
0.70661
false
false
false
false
calebkleveter/Ether
refs/heads/master
Sources/Ether/Search.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 Caleb Kleveter // // 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 Helpers import Command import Console import Vapor public final class Search: Command { public var arguments: [CommandArgument] = [ CommandArgument.argument(name: "name", help: ["The name of the package to search for."]) ] public var options: [CommandOption] = [ CommandOption.value(name: "max-results", default: "20", help: [ "The maximum number of results that will be returned.", "This defaults to 20." ]) ] public var help: [String] = ["Searches for availible packages."] public init() {} public func run(using context: CommandContext) throws -> EventLoopFuture<Void> { let searching = context.console.loadingBar(title: "Searching") _ = searching.start(on: context.container) let client = try context.container.make(Client.self) let name = try context.argument("name") let maxResults = context.options["max-results"] ?? "20" guard let max = Int(maxResults), max <= 100 && max > 0 else { throw EtherError(identifier: "badMaxResults", reason: "`max-results` value must be an integer, less than or equal to 100, and greater than 0") } let token = try Configuration.get().token() let response = client.get("https://package.vapor.cloud/packages/search?name=\(name)&limit=\(max)", headers: ["Authorization": "Bearer \(token)"]) return response.flatMap(to: [PackageDescription].self) { response in searching.succeed() return response.content.get([PackageDescription].self, at: "repositories") }.map(to: Void.self) { packages in packages.forEach { package in package.print(on: context) context.console.print() } } } } struct PackageDescription: Codable { let nameWithOwner: String let description: String? let licenseInfo: String? let stargazers: Int? func print(on context: CommandContext) { if let description = self.description { context.console.info(nameWithOwner + ": ", newLine: false) context.console.print(description) } else { context.console.info(self.nameWithOwner) } if let licenseInfo = self.licenseInfo { let license = licenseInfo == "NOASSERTION" ? "Unknown" : licenseInfo context.console.print("License: " + license) } if let stars = self.stargazers { context.console.print("Stars: " + String(stars)) } } }
75eb3af9fec6e8d1c1e0ad325d2a0319
39.55914
154
0.649258
false
false
false
false
appsandwich/ppt2rk
refs/heads/master
ppt2rk/KeychainPasswordItem.swift
mit
1
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A struct for accessing generic password keychain items. */ /* Sample code project: GenericKeychain Version: 4.0 IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2016 Apple Inc. All Rights Reserved. */ import Foundation struct KeychainPasswordItem { // MARK: Types enum KeychainError: Error { case noPassword case unexpectedPasswordData case unexpectedItemData case unhandledError(status: OSStatus) } // MARK: Properties let service: String private(set) var account: String let accessGroup: String? // MARK: Intialization init(service: String, account: String, accessGroup: String? = nil) { self.service = service self.account = account self.accessGroup = accessGroup } // MARK: Keychain access func readPassword() throws -> String { /* Build a query to find the item that matches the service, account and access group. */ var query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) query[kSecMatchLimit as String] = kSecMatchLimitOne query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecReturnData as String] = kCFBooleanTrue // Try to fetch the existing keychain item that matches the query. var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } // Check the return status and throw an error if appropriate. guard status != errSecItemNotFound else { throw KeychainError.noPassword } guard status == noErr else { throw KeychainError.unhandledError(status: status) } // Parse the password string from the query result. guard let existingItem = queryResult as? [String : AnyObject], let passwordData = existingItem[kSecValueData as String] as? Data, let password = String(data: passwordData, encoding: String.Encoding.utf8) else { throw KeychainError.unexpectedPasswordData } return password } func savePassword(_ password: String) throws { // Encode the password into an Data object. let encodedPassword = password.data(using: String.Encoding.utf8)! do { // Check for an existing item in the keychain. try _ = readPassword() // Update the existing item with the new password. var attributesToUpdate = [String : AnyObject]() attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject? let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) // Throw an error if an unexpected status was returned. guard status == noErr else { throw KeychainError.unhandledError(status: status) } } catch KeychainError.noPassword { /* No password was found in the keychain. Create a dictionary to save as a new keychain item. */ var newItem = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) newItem[kSecValueData as String] = encodedPassword as AnyObject? // Add a the new item to the keychain. let status = SecItemAdd(newItem as CFDictionary, nil) // Throw an error if an unexpected status was returned. guard status == noErr else { throw KeychainError.unhandledError(status: status) } } } mutating func renameAccount(_ newAccountName: String) throws { // Try to update an existing item with the new account name. var attributesToUpdate = [String : AnyObject]() attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject? let query = KeychainPasswordItem.keychainQuery(withService: service, account: self.account, accessGroup: accessGroup) let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) // Throw an error if an unexpected status was returned. guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) } self.account = newAccountName } func deleteItem() throws { // Delete the existing item from the keychain. let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) let status = SecItemDelete(query as CFDictionary) // Throw an error if an unexpected status was returned. guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) } } static func passwordItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainPasswordItem] { // Build a query for all items that match the service and access group. var query = KeychainPasswordItem.keychainQuery(withService: service, accessGroup: accessGroup) query[kSecMatchLimit as String] = kSecMatchLimitAll query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecReturnData as String] = kCFBooleanFalse // Fetch matching items from the keychain. var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } // If no items were found, return an empty array. guard status != errSecItemNotFound else { return [] } // Throw an error if an unexpected status was returned. guard status == noErr else { throw KeychainError.unhandledError(status: status) } // Cast the query result to an array of dictionaries. guard let resultData = queryResult as? [[String : AnyObject]] else { throw KeychainError.unexpectedItemData } // Create a `KeychainPasswordItem` for each dictionary in the query result. var passwordItems = [KeychainPasswordItem]() for result in resultData { guard let account = result[kSecAttrAccount as String] as? String else { throw KeychainError.unexpectedItemData } let passwordItem = KeychainPasswordItem(service: service, account: account, accessGroup: accessGroup) passwordItems.append(passwordItem) } return passwordItems } // MARK: Convenience private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String : AnyObject] { var query = [String : AnyObject]() query[kSecClass as String] = kSecClassGenericPassword query[kSecAttrService as String] = service as AnyObject? if let account = account { query[kSecAttrAccount as String] = account as AnyObject? } if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup as AnyObject? } return query } }
298609856daeda6adba8c73f39f1847b
43.151111
144
0.686229
false
false
false
false
davejlin/treehouse
refs/heads/master
swift/swift2/autolayout-format-strings/AutoLayoutFormatStrings/ViewController.swift
unlicense
1
// // ViewController.swift // AutoLayoutFormatStrings // // Created by Lin David, US-205 on 10/3/16. // Copyright © 2016 Lin David. All rights reserved. // import UIKit class ViewController: UIViewController { let orangeView = UIView() let purpleView = UIView() let blueView = UIView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. orangeView.backgroundColor = UIColor(red: 255/255.0, green: 148/255.0, blue: 0.0, alpha: 1.0) purpleView.backgroundColor = UIColor(red: 187/255.0, green: 44/255.0, blue: 162/255.0, alpha: 1.0) blueView.backgroundColor = UIColor(red: 122/255.0, green: 206/255.0, blue: 255/255.0, alpha: 1.0) orangeView.translatesAutoresizingMaskIntoConstraints = false purpleView.translatesAutoresizingMaskIntoConstraints = false blueView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(orangeView) view.addSubview(purpleView) view.addSubview(blueView) let views: [String: AnyObject] = [ "orangeView": orangeView, "purpleView": purpleView, "blueView": blueView, "topLayoutGuide": self.topLayoutGuide ] let metrics: [String: AnyObject] = [ "orangeViewWidth": 200, "orangeViewHeight": 57, "standardOffset": 8, "bottomSpaceOffset": 50 ] orangeView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true let constraints1 = NSLayoutConstraint.constraintsWithVisualFormat("H:[orangeView(orangeViewWidth)]", options: [], metrics: metrics, views: views) view.addConstraints(constraints1) let constraints2 = NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-standardOffset-[purpleView]-standardOffset-[orangeView(orangeViewHeight)]-bottomSpaceOffset-|", options: [], metrics: metrics, views: views) view.addConstraints(constraints2) let constraints3 = NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-standardOffset-[blueView]-standardOffset-[orangeView]", options: [], metrics: metrics, views: views) view.addConstraints(constraints3) let constraints4 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-standardOffset-[purpleView(==blueView)]-standardOffset-[blueView]-standardOffset-|", options: [], metrics: metrics, views: views) view.addConstraints(constraints4) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20953117bf68ea901176a500bce3fcb5
38.277778
234
0.65983
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/BusinessLayer/Services/Pin/Repository/PinRepository.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class PinRepository: PinRepositoryProtocol { let keychain: Keychain init(keychain: Keychain) { self.keychain = keychain } var hasPin: Bool { return keychain.passphrase != nil } var pin: [String]? { guard let passphrase = keychain.passphrase else { return nil } return passphrase.map { String($0) } } func savePin(_ pin: [String]) { let pin = pin.joined() keychain.passphrase = pin } func deletePin() { keychain.passphrase = nil } }
dae55db9529737e4385d0d1d4222c0ac
16.941176
54
0.637705
false
false
false
false
GMSLabs/Hyber-SDK-iOS
refs/heads/swift-3.0
Example/Hyber/Sources/ESRefreshComponent.swift
apache-2.0
1
// // ESRefreshComponent.swift // // Created by egg swift on 16/4/7. // Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit public typealias ESRefreshHandler = (() -> ()) open class ESRefreshComponent: UIView { fileprivate static var context = "ESRefreshKVOContext" fileprivate static let offsetKeyPath = "contentOffset" fileprivate static let contentSizeKeyPath = "contentSize" open weak var scrollView: UIScrollView? /// @param handler Refresh callback method open var handler: ESRefreshHandler? /// @param animator Animated view refresh controls, custom must comply with the following two protocol open var animator: (ESRefreshProtocol & ESRefreshAnimatorProtocol)! open var animating: Bool = false open var loading: Bool = false { didSet { if loading != oldValue { if loading { startAnimating() } else { stopAnimating() } } } } public override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [.flexibleLeftMargin, .flexibleWidth, .flexibleRightMargin] } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshAnimator.init() } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler, customAnimator animator: ESRefreshProtocol & ESRefreshAnimatorProtocol) { self.init(frame: frame) self.handler = handler self.animator = animator } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeObserver() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) /// Remove observer from superview immediately self.removeObserver() DispatchQueue.main.async { [weak self, newSuperview] in guard let weakSelf = self else { return } /// Add observer to new superview in next runloop weakSelf.addObserver(newSuperview) } } open override func didMoveToSuperview() { super.didMoveToSuperview() self.scrollView = self.superview as? UIScrollView if let _ = animator { let v = animator.view if v.superview == nil { let inset = animator.insets self.addSubview(v) v.frame = CGRect.init(x: inset.left, y: inset.right, width: self.bounds.size.width - inset.left - inset.right, height: self.bounds.size.height - inset.top - inset.bottom) v.autoresizingMask = [ .flexibleWidth, .flexibleTopMargin, .flexibleHeight, .flexibleBottomMargin ] } } } } extension ESRefreshComponent /* KVO methods */ { fileprivate func addObserver(_ view: UIView?) { if let scrollView = view as? UIScrollView { scrollView.addObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) scrollView.addObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) } } fileprivate func removeObserver() { if let scrollView = superview as? UIScrollView { scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, context: &ESRefreshComponent.context) scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, context: &ESRefreshComponent.context) } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &ESRefreshComponent.context { guard isUserInteractionEnabled == true && isHidden == false else { return } if keyPath == ESRefreshComponent.contentSizeKeyPath { sizeChangeAction(object: object as AnyObject?, change: change) } else if keyPath == ESRefreshComponent.offsetKeyPath { offsetChangeAction(object: object as AnyObject?, change: change) } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } } public extension ESRefreshComponent /* Action */ { public func startAnimating() -> Void { animating = true } public func stopAnimating() -> Void { animating = false } // ScrollView contentSize change action public func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } // ScrollView offset change action public func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } }
5b7e9545917c61de798f65acd5d41e5b
37.680723
156
0.643358
false
false
false
false
zhiquan911/CHKLineChart
refs/heads/master
CHKLineChart/CHKLineChart/DemoSelectViewController.swift
mit
1
// // ViewController.swift // CHKLineChart // // Created by Chance on 16/8/31. // Copyright © 2016年 Chance. All rights reserved. // import UIKit import CHKLineChartKit class DemoSelectViewController: UIViewController { @IBOutlet var tableView: UITableView! let demo: [Int: (String, String)] = [ 0: ("K线一般功能演示", "ChartDemoViewController"), 1: ("K线风格设置演示", "CustomStyleViewController"), 2: ("K线商业定制例子", "ChartCustomDesignViewController"), 3: ("K线简单线段例子", "ChartFullViewController"), 4: ("K线静态图片例子", "ChartImageViewController"), 5: ("K线列表图表例子", "ChartInTableViewController"), 6: ("盘口深度图表例子", "DepthChartDemoViewController"), ] override func viewDidLoad() { super.viewDidLoad() } } extension DemoSelectViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.demo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "DemoCell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "DemoCell") } cell?.textLabel?.text = self.demo[indexPath.row]!.0 return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let story = UIStoryboard.init(name: "Main", bundle: nil) let name = self.demo[indexPath.row]!.1 let vc = story.instantiateViewController(withIdentifier: name) self.present(vc, animated: true, completion: nil) } }
f2c8b2cf34807f4d3dfa20821d6fc1bc
30.383333
100
0.65162
false
false
false
false
NicholasWon/algorithmStudy
refs/heads/master
Baekjun/1065.swift
mit
1
import Foundation /* * 문제: 어떤 양의 정수 X의 자리수가 등차수열을 이룬다면, 그 수를 한수라고 한다. * 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. * N이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오. * * 문제 링크: https://www.acmicpc.net/problem/1065 * 예제입력: 110 * 예제출력: 99 */ let n = Int(readLine()!)! /* * 입력된 수의 각 자리수가 등차수열 관계를 갖는지(=한수) 여부 확인, * 99 이하의 수는 무조건 참 * * 입력된 수를 배열로 만들고, 엇갈리게 배치해서 각 원소간의 차를 계산 * 123 -> [1, 2] - [2, 3] = [-1, -1] => 등차수열! */ func isHanSu(_ i :Int) -> Bool { if i/100 == 0 { return true } // 99 이하의 수는 무조건 한수 let str = "\(i)" // 입력된 수를 문자열로 변환, "123" let val1 = str.substring(to: str.index(before: str.endIndex)) .characters.map { String($0) } .map { Int($0)! } // 맨 뒷자리 수를 없애고 배열로 변환, [1, 2] let val2 = str.substring(from: str.index(after: str.startIndex)) .characters.map { String($0) } .map { Int($0)! } // 맨 앞자리 수를 없애고 배열로 변환, [2, 3] let diff = val1[0] - val2[0] // 원소간 차이값, -1 return zip(val1, val2).map { $0 - $1 } .filter { $0 != diff } .count == 0 // 차이값과 다른 원소가 존재하는지 확인, 한 개라도 존재하면 false } print(Array(1...n).filter { isHanSu($0) }.count) // 한수의 조건을 만족하는 원소 갯수 출력
45668b530f317c5da68cc4360a3f82dd
31.921053
79
0.514788
false
false
false
false
universeiscool/MediaPickerController
refs/heads/master
MediaPickerController/MomentsCollectionViewFlowLayout.swift
mit
1
// // MomentsCollectionViewFlowLayout.swift // MediaPickerController // // Created by Malte Schonvogel on 24.11.15. // Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved. // import UIKit let kDecorationReuseIdentifier = "MomentsCollectionViewDecoration" class MomentsCollectionViewFlowLayout: UICollectionViewFlowLayout { var headerAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]() var footerAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]() var backgroundAttributes = [NSIndexPath:MediaPickerCollectionViewLayoutAttributes]() var cellAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]() private var contentSize = CGSizeZero var viewPortWidth: CGFloat { get { return self.collectionView!.frame.width - self.collectionView!.contentInset.left - self.collectionView!.contentInset.right } } var viewPortAvailableSize: CGFloat { get { return self.viewPortWidth - self.sectionInset.left - self.sectionInset.right } } weak var delegate: MomentsCollectionViewFlowLayoutDelegate? { get{ return self.collectionView!.delegate as? MomentsCollectionViewFlowLayoutDelegate } } // Caution! This prevents layout calculations var sizeOfViewsNeverChange:Bool = false override init() { super.init() setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { registerClass(MomentsCollectionDecorationView.self, forDecorationViewOfKind: kDecorationReuseIdentifier) } override class func layoutAttributesClass() -> AnyClass { return MediaPickerCollectionViewLayoutAttributes.self } private func clearVariables() { headerAttributes.removeAll() cellAttributes.removeAll() footerAttributes.removeAll() backgroundAttributes.removeAll() contentSize = CGSizeZero } override func prepareLayout() { guard let sectionAmount = collectionView?.numberOfSections() else { return } if sectionAmount == 0 || (sizeOfViewsNeverChange && sectionAmount == backgroundAttributes.count && contentSize.width == viewPortWidth) { return } let itemsPerRow = Int(viewPortWidth / itemSize.width) // Initialize variables clearVariables() // Shortcut let viewWidth = collectionView!.bounds.width for section in 0..<sectionAmount { let indexPath = NSIndexPath(forItem: 0, inSection: section) // HeaderSize let headerSize = referenceSizeForHeaderInSection(section) let hLa = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withIndexPath: indexPath) hLa.frame = CGRect(x: 0, y: contentSize.height, width: viewWidth, height: headerSize.height) headerAttributes[indexPath] = hLa // SectionSize let sectionOffset = CGPoint(x: 0, y: contentSize.height + headerSize.height) let itemsAmount:Int = collectionView!.numberOfItemsInSection(section) let fractions = fractionize(itemsAmount, itemsAmountPerRow: itemsPerRow, section: section) let sectionSize = setFramesForItems(fractions: fractions, section: section, sectionOffset: sectionOffset) // FooterSize let footerSize = referenceSizeForFooterInSection(section) let fLa = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withIndexPath: indexPath) fLa.frame = CGRect(x: 0, y: contentSize.height + headerSize.height + sectionSize.height, width: viewWidth, height: footerSize.height) footerAttributes[indexPath] = fLa // BackgroundSize let bLa = MediaPickerCollectionViewLayoutAttributes(forDecorationViewOfKind: kDecorationReuseIdentifier, withIndexPath: indexPath) bLa.frame = CGRect(x: 0, y: contentSize.height, width: viewWidth, height: headerSize.height + sectionSize.height - sectionInset.bottom) if let selected = delegate?.sectionIsSelected(section) { bLa.selected = selected } backgroundAttributes[indexPath] = bLa // ContentSize contentSize = CGSize(width: sectionSize.width, height: contentSize.height + headerSize.height + sectionSize.height + footerSize.height) } } private func fractionize(let amount:Int, itemsAmountPerRow:Int, section:Int) -> [[Int]] { var result = [[Int]]() if amount == 0 { return result } let rest:Int = amount % itemsAmountPerRow // Quick & Dirty if amount == rest { result.append((0..<amount).map({ $0 })) } else if rest > 0 && rest <= Int(ceil(Float(itemsAmountPerRow/2))) && amount >= rest + itemsAmountPerRow { let newRest = rest + itemsAmountPerRow let divider = Int(ceil(Float(newRest) / Float(itemsAmountPerRow/2))) result += (0..<newRest).map({$0}).splitBy(divider).reverse() result += (newRest..<amount).map({$0}).splitBy(itemsAmountPerRow) } else { let first = (0..<rest).map({ $0 }) if !first.isEmpty { result.append(first) } let second = (rest..<amount).map({ $0 }).splitBy(itemsAmountPerRow) if !second.isEmpty { result += second } } return result } private func setFramesForItems(fractions fractions:[[Int]], section:Int, sectionOffset: CGPoint) -> CGSize { var contentMaxValueInScrollDirection = CGFloat(0) var offset = CGPoint(x: sectionOffset.x + sectionInset.left, y: sectionOffset.y + sectionInset.top) for fraction in fractions { let itemsPerRow = fraction.count let itemWidthHeight:CGFloat = (viewPortAvailableSize - minimumInteritemSpacing * CGFloat(itemsPerRow-1)) / CGFloat(itemsPerRow) offset.x = sectionOffset.x + sectionInset.left for itemIndex in fraction { let indexPath = NSIndexPath(forItem: itemIndex, inSection: section) let frame = CGRectMake(offset.x, offset.y, itemWidthHeight, itemWidthHeight) let la = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) la.frame = frame cellAttributes[indexPath] = la contentMaxValueInScrollDirection = CGRectGetMaxY(frame) offset.x += itemWidthHeight + minimumInteritemSpacing } offset.y += itemWidthHeight + minimumLineSpacing } return CGSize(width: viewPortWidth, height: contentMaxValueInScrollDirection - sectionOffset.y + sectionInset.bottom) } // MARK: Delegate Helpers private func referenceSizeForHeaderInSection(section:Int) -> CGSize { if let headerSize = self.delegate?.collectionView?(collectionView!, layout: self, referenceSizeForHeaderInSection: section){ return headerSize } return headerReferenceSize } private func referenceSizeForFooterInSection(section:Int) -> CGSize { if let footerSize = self.delegate?.collectionView?(collectionView!, layout: self, referenceSizeForFooterInSection: section){ return footerSize } return footerReferenceSize } override func collectionViewContentSize() -> CGSize { return contentSize } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var lA = [UICollectionViewLayoutAttributes]() for section in 0..<collectionView!.numberOfSections() { let sectionIndexPath = NSIndexPath(forItem: 0, inSection: section) // HeaderAttributes if let hA = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(hA.frame.size, CGSizeZero) && CGRectIntersectsRect(hA.frame, rect) { lA.append(hA) } // ItemAttributes for item in 0..<collectionView!.numberOfItemsInSection(section) { if let la = cellAttributes[NSIndexPath(forItem: item, inSection: section)] where CGRectIntersectsRect(rect, la.frame) { lA.append(la) } } // FooterAttributes if let fA = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionFooter, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(fA.frame.size, CGSizeZero) && CGRectIntersectsRect(fA.frame, rect) { lA.append(fA) } // BackgroundAttributes if let bA = layoutAttributesForDecorationViewOfKind(kDecorationReuseIdentifier, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(bA.frame.size, CGSizeZero) && CGRectIntersectsRect(bA.frame, rect) { lA.append(bA) } } return lA } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return cellAttributes[indexPath] } override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { switch elementKind { case UICollectionElementKindSectionHeader: return headerAttributes[indexPath] case UICollectionElementKindSectionFooter: return footerAttributes[indexPath] default: return nil } } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { let oldBounds = collectionView!.bounds if CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds) || CGRectGetHeight(newBounds) != CGRectGetHeight(oldBounds) { return true } return false } override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let la = backgroundAttributes[indexPath] if let selected = delegate?.sectionIsSelected(indexPath.section) { la?.selected = selected } return la } } public protocol MomentsCollectionViewFlowLayoutDelegate: UICollectionViewDelegateFlowLayout { func sectionIsSelected(section:Int) -> Bool } class MediaPickerCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes { var selected = false } extension Array { func splitBy(subSize: Int) -> [[Element]] { return 0.stride(to: self.count, by: subSize).map { startIndex in let endIndex = startIndex.advancedBy(subSize, limit: self.count) return Array(self[startIndex ..< endIndex]) } } }
647ed8a29e4be989dc55256279afd5d0
38.229452
229
0.647197
false
false
false
false
adamnemecek/SortedArray.swift
refs/heads/master
Sources/Extension.swift
mit
1
// // Extension.swift // RangeDB // // Created by Adam Nemecek on 4/29/17. // Copyright © 2017 Adam Nemecek. All rights reserved. // import Foundation public typealias Predicate<Element> = (Element) -> Bool public typealias Relation<Element> = (Element, Element) -> Bool extension CountableRange { var mid : Bound { return lowerBound.advanced(by: count / 2) } } extension Collection { subscript(safe index: Index) -> Iterator.Element? { @inline(__always) get { guard (startIndex..<endIndex).contains(index) else { return nil } return self[index] } } subscript(after i: Index) -> Iterator.Element? { return self[safe: index(after: i)] } } extension BidirectionalCollection { subscript(before i: Index) -> Iterator.Element? { return self[safe: index(before: i)] } var lastIndex: Index { return index(before: endIndex) } } extension BidirectionalCollection { func lastIndex(where: (Iterator.Element) -> Bool) -> Index? { return sequence(first: lastIndex) { /// note that the last generated element is still startIndex guard $0 > self.startIndex else { return nil } return self.index(before: $0) }.first { `where`(self[$0]) } } } extension Collection where Iterator.Element : Equatable, SubSequence.Iterator.Element == Iterator.Element { func unique() -> [Iterator.Element] { /// unique, we could call `contains` as we go through, but this is linear time return match.map { fst in var prev = fst.head return [prev] + fst.tail.filter { e in defer { prev = e } return e != prev } } ?? [] } } internal extension Collection { var match: (head: Iterator.Element, tail: SubSequence)? { return first.map { ($0, dropFirst()) } } } extension Sequence { func all(predicate: Predicate<Iterator.Element>) -> Bool { return !contains { !predicate($0) } } }
27dd5ddabce62cf060bf783b9068599f
24.662651
107
0.583099
false
false
false
false
Sephiroth87/C-swifty4
refs/heads/master
Common/ScaleFilter.swift
mit
1
// // ScaleFilter.swift // C-swifty4 Mac // // Created by Fabio on 16/11/2017. // Copyright © 2017 orange in a day. All rights reserved. // import MetalKit // Simple 2x texture scaler // TODO: Maybe implement other scaling factors if the drawing surface is closer to one of them (less blur when scaling) class ScaleFilter { internal let texture: MTLTexture private let kernel: MTLComputePipelineState private let threadGroupSize = MTLSizeMake(16, 16, 1) private let threadGroupCount = MTLSizeMake(64, 64, 1) init(device: MTLDevice, library: MTLLibrary, usesMtlBuffer: Bool) { let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: 1024, height: 1024, mipmapped: false) textureDescriptor.usage = [.shaderRead, .shaderWrite] if usesMtlBuffer, #available(OSX 10.13, iOS 8.0, tvOS 9.0, *) { let buffer = device.makeBuffer(length: 1024 * 1024 * 4, options: [])! texture = buffer.makeTexture(descriptor: textureDescriptor, offset: 0, bytesPerRow: 1024 * 4)! } else { texture = device.makeTexture(descriptor: textureDescriptor)! } let function = library.makeFunction(name: "scale")! kernel = try! device.makeComputePipelineState(function: function) } func apply(to: MTLTexture, with commandBuffer: MTLCommandBuffer) { let encoder = commandBuffer.makeComputeCommandEncoder() encoder?.setComputePipelineState(kernel) encoder?.setTexture(to, index: 0) encoder?.setTexture(texture, index: 1) encoder?.dispatchThreadgroups(threadGroupCount, threadsPerThreadgroup: threadGroupSize) encoder?.endEncoding() } }
217ab5cce6f810490ce2e2ff1db58bd5
40.357143
143
0.690271
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/AssetSparklineView/AssetSparklineView.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxRelay import RxSwift public final class AssetSparklineView: UIView { // MARK: - Injected public var presenter: AssetSparklinePresenter! { willSet { presenterDisposeBag = DisposeBag() } didSet { guard presenter != nil else { pathRelay.accept(nil) return } calculate() } } // MARK: - Private Properties private var path: Driver<UIBezierPath?> { pathRelay.asDriver() } private var lineColor: Driver<UIColor> { .just(presenter.lineColor) } private var fillColor: Driver<UIColor> { .just(.clear) } private var lineWidth: Driver<CGFloat> { .just(attributes.lineWidth) } private let pathRelay: BehaviorRelay<UIBezierPath?> = BehaviorRelay(value: nil) private let shape = CAShapeLayer() private let disposeBag = DisposeBag() private var presenterDisposeBag = DisposeBag() private var attributes: SparklineAttributes { .init(size: frame.size) } // MARK: - Init override public init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func calculate() { let calculator = SparklineCalculator(attributes: attributes) presenter .state .compactMap { state -> UIBezierPath? in switch state { case .valid(prices: let prices): return calculator.sparkline(with: prices) case .empty, .invalid, .loading: return nil } } .bindAndCatch(to: pathRelay) .disposed(by: presenterDisposeBag) lineColor .drive(shape.rx.strokeColor) .disposed(by: presenterDisposeBag) fillColor .drive(shape.rx.fillColor) .disposed(by: presenterDisposeBag) lineWidth .drive(shape.rx.lineWidth) .disposed(by: presenterDisposeBag) } private func setup() { if layer.sublayers == nil { shape.bounds = frame shape.position = center layer.addSublayer(shape) } path .drive(shape.rx.path) .disposed(by: disposeBag) } }
8aa9fd569425cc3a642c26c1b7e8766f
23.568627
83
0.561453
false
false
false
false
iachievedit/moreswift
refs/heads/master
cmdline_translator/Sources/CommandInterpreter.swift
apache-2.0
1
// Copyright 2015 iAchieved.it LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 statements import Foundation import Glibc // Enumerations enum CommandType { case None case Translate case SetFrom case SetTo case Quit } // Structs struct Command { var type:CommandType var data:String } // Classes class CommandInterpreter { // Read-only computed property var prompt:String { return "\(translationCommand.from)->\(translationCommand.to)" } // Class constant let delim:Character = "\n" init() { } func start() { let readThread = Thread(){ var input:String = "" print("To set input language, type 'from LANG'") print("To set output language, type 'to LANG'") print("Type 'quit' to exit") self.displayPrompt() while true { let c = Character(UnicodeScalar(UInt32(fgetc(stdin)))!) if c == self.delim { let command = self.parseInput(input:input) self.doCommand(command:command) input = "" // Clear input self.displayPrompt() } else { input.append(c) } } } readThread.start() } func displayPrompt() { print("\(self.prompt): ", terminator:"") } func parseInput(input:String) -> Command { var commandType:CommandType var commandData:String = "" // Splitting a string let tokens = input.characters.split{$0 == " "}.map(String.init) // guard statement to validate that there are tokens guard tokens.count > 0 else { return Command(type:CommandType.None, data:"") } switch tokens[0] { case "quit": commandType = .Quit case "from": commandType = .SetFrom commandData = tokens[1] case "to": commandType = .SetTo commandData = tokens[1] default: commandType = .Translate commandData = input } return Command(type:commandType, data:commandData) } func doCommand(command:Command) { switch command.type { case .Quit: exit(0) case .SetFrom: translationCommand.from = command.data case .SetTo: translationCommand.to = command.data case .Translate: translationCommand.text = command.data nc.post(Notification(name:INPUT_NOTIFICATION, object:nil)) case .None: break } } }
5832e1d8b92014a3ebd599307f033743
22.578512
75
0.64143
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
RouterPattern/app/RouterPattern/RouterPatterm/Router.swift
mit
1
// // Router.swift // RouterPatterm // // Created by 双泉 朱 on 17/4/12. // Copyright © 2017年 Doubles_Z. All rights reserved. // import UIKit class Router { static let shareRouter = Router() var params: [String : Any]? var routers: [String : Any]? fileprivate let map = ["J1" : "Controller"] func guardRouters(finishedCallback : @escaping () -> ()) { Http.requestData(.get, URLString: "http://localhost:3001/api/J1/getRouters") { (response) in guard let result = response as? [String : Any] else { return } guard let data:[String : Any] = result["data"] as? [String : Any] else { return } guard let routers:[String : Any] = data["routers"] as? [String : Any] else { return } self.routers = routers finishedCallback() } } } extension Router { func addParam(key: String, value: Any) { params?[key] = value } func clearParams() { params?.removeAll() } func push(_ path: String) { guardRouters { guard let state = self.routers?[path] as? String else { return } if state == "app" { guard let nativeController = NSClassFromString("RouterPatterm.\(self.map[path]!)") as? UIViewController.Type else { return } currentController?.navigationController?.pushViewController(nativeController.init(), animated: true) } if state == "web" { let host = "http://localhost:3000/" var query = "" let ref = "client=app" guard let params = self.params else { return } for (key, value) in params { query += "\(key)=\(value)&" } self.clearParams() let webViewController = WebViewController("\(host)\(path)?\(query)\(ref)") currentController?.navigationController?.pushViewController(webViewController, animated: true) } } } }
54f0b8c5c4d86f0c8bc000e87311b1c7
31.089552
140
0.522326
false
false
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/UI/Authorization/AuthorizationiPhonePresentationController.swift
apache-2.0
14
final class AuthorizationiPhonePresentationController: UIPresentationController { override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() (presentedViewController as? AuthorizationViewController)?.chromeView.frame = containerView!.bounds presentedView?.frame = frameOfPresentedViewInContainerView } override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() guard let presentedViewController = presentedViewController as? AuthorizationViewController, let coordinator = presentedViewController.transitionCoordinator, let containerView = containerView else { return } containerView.addSubview(presentedView!) presentedViewController.containerView = containerView presentedViewController.chromeView.frame = containerView.bounds presentedViewController.chromeView.alpha = 0 coordinator.animate(alongsideTransition: { _ in presentedViewController.chromeView.alpha = 1 }, completion: nil) } override func dismissalTransitionWillBegin() { super.dismissalTransitionWillBegin() guard let presentedViewController = presentedViewController as? AuthorizationViewController, let coordinator = presentedViewController.transitionCoordinator, let presentedView = presentedView else { return } coordinator.animate(alongsideTransition: { _ in presentedViewController.chromeView.alpha = 0 }, completion: { _ in presentedView.removeFromSuperview() }) } }
d9c75b194731d3fbb70abb1034628425
41.305556
103
0.787262
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Generators/Oscillators/FM Oscillator/AKFMOscillatorPresets.swift
mit
1
// // AKFMOscillatorPresets.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Preset for the AKFMOscillator public extension AKFMOscillator { /// Stun Ray Preset public func presetStunRay() { baseFrequency = 200 carrierMultiplier = 90 modulatingMultiplier = 10 modulationIndex = 25 } /// Fog Horn Preset public func presetFogHorn() { baseFrequency = 25 carrierMultiplier = 10 modulatingMultiplier = 5 modulationIndex = 10 } /// Buzzer Preset public func presetBuzzer() { baseFrequency = 400 carrierMultiplier = 28 modulatingMultiplier = 0.5 modulationIndex = 100 } /// Spiral Preset public func presetSpiral() { baseFrequency = 5 carrierMultiplier = 280 modulatingMultiplier = 0.2 modulationIndex = 100 } /// Wobble Preset public func presetWobble() { baseFrequency = 20 carrierMultiplier = 10 modulatingMultiplier = 0.9 modulationIndex = 20 } }
fd362ff85f5f27886c24e32ec3e4910f
22.078431
62
0.617672
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/PresentationLayer/Wallet/Settings/Module/SettingsModule.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class SettingsModule { class func create(app: Application) -> SettingsModuleInput { let router = SettingsRouter() let presenter = SettingsPresenter() let interactor = SettingsInteractor() let viewController = R.storyboard.settings.settingsViewController()! interactor.output = presenter viewController.output = presenter presenter.view = viewController presenter.router = router presenter.interactor = interactor router.app = app // Injection let keychain = Keychain() interactor.walletDataStoreService = WalletDataStoreService() interactor.walletRepository = app.walletRepository interactor.keystore = KeystoreService() interactor.keychain = keychain interactor.pushService = PushService() interactor.accountService = AccountService(keychain: keychain) interactor.biometryService = BiometryService() interactor.pushConfigurator = app.pushConfigurator return presenter } }
219e7221878d588ce03c724130efad39
26.35
72
0.728519
false
false
false
false
Alecrim/AlecrimCoreData
refs/heads/master
Sources/Fetch Request Controller/FetchRequestController.swift
mit
1
// // FetchRequestController.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 11/03/18. // Copyright © 2018 Alecrim. All rights reserved. // import Foundation import CoreData // // we cannot inherit from `NSFetchedResultsController` here because the error: // "inheritance from a generic Objective-C class 'NSFetchedResultsController' must bind type parameters of // 'NSFetchedResultsController' to specific concrete types" // and // `FetchRequestController<Entity: ManagedObject>: NSFetchedResultsController<NSFetchRequestResult>` will not work for us // (curiously the "rawValue" inside our class is accepted to be `NSFetchedResultsController<Entity>`) // // MARK: - public final class FetchRequestController<Entity: ManagedObject> { // MARK: - public let fetchRequest: FetchRequest<Entity> public let rawValue: NSFetchedResultsController<Entity> internal let rawValueDelegate: FetchedResultsControllerDelegate<Entity> fileprivate let initialPredicate: Predicate<Entity>? fileprivate let initialSortDescriptors: [SortDescriptor<Entity>]? private var didPerformFetch = false // MARK: - public convenience init<Value>(query: Query<Entity>, sectionName sectionNameKeyPathClosure: @autoclosure () -> KeyPath<Entity, Value>, cacheName: String? = nil) { let sectionNameKeyPath = sectionNameKeyPathClosure().pathString self.init(fetchRequest: query.fetchRequest, context: query.context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public convenience init(query: Query<Entity>, sectionNameKeyPath: String? = nil, cacheName: String? = nil) { self.init(fetchRequest: query.fetchRequest, context: query.context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public convenience init<Value>(fetchRequest: FetchRequest<Entity>, context: ManagedObjectContext, sectionName sectionNameKeyPathClosure: @autoclosure () -> KeyPath<Entity, Value>, cacheName: String? = nil) { let sectionNameKeyPath = sectionNameKeyPathClosure().pathString self.init(fetchRequest: fetchRequest, context: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public init(fetchRequest: FetchRequest<Entity>, context: ManagedObjectContext, sectionNameKeyPath: String? = nil, cacheName: String? = nil) { self.fetchRequest = fetchRequest self.rawValue = NSFetchedResultsController(fetchRequest: fetchRequest.toRaw() as NSFetchRequest<Entity>, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) self.rawValueDelegate = FetchedResultsControllerDelegate<Entity>() self.initialPredicate = fetchRequest.predicate self.initialSortDescriptors = fetchRequest.sortDescriptors // self.rawValue.delegate = self.rawValueDelegate } // MARK: - public func performFetch() { try! self.rawValue.performFetch() self.didPerformFetch = true } public func performFetchIfNeeded() { if !self.didPerformFetch { try! self.rawValue.performFetch() self.didPerformFetch = true } } } // MARK: - extension FetchRequestController { public var fetchedObjects: [Entity]? { self.performFetchIfNeeded() return self.rawValue.fetchedObjects } public func object(at indexPath: IndexPath) -> Entity { self.performFetchIfNeeded() return self.rawValue.object(at: indexPath) } public func indexPath(for object: Entity) -> IndexPath? { self.performFetchIfNeeded() return self.rawValue.indexPath(forObject: object) } } extension FetchRequestController { public func numberOfSections() -> Int { self.performFetchIfNeeded() return self.sections.count } public func numberOfObjects(inSection section: Int) -> Int { self.performFetchIfNeeded() return self.sections[section].numberOfObjects } } extension FetchRequestController { public var sections: [FetchedResultsSectionInfo<Entity>] { self.performFetchIfNeeded() guard let result = self.rawValue.sections?.map({ FetchedResultsSectionInfo<Entity>(rawValue: $0) }) else { fatalError("performFetch: hasn't been called.") } return result } public func section(forSectionIndexTitle title: String, at sectionIndex: Int) -> Int { self.performFetchIfNeeded() return self.rawValue.section(forSectionIndexTitle: title, at: sectionIndex) } } extension FetchRequestController { public func sectionIndexTitle(forSectionName sectionName: String) -> String? { self.performFetchIfNeeded() return self.rawValue.sectionIndexTitle(forSectionName: sectionName) } public var sectionIndexTitles: [String] { self.performFetchIfNeeded() return self.rawValue.sectionIndexTitles } } // MARK: - extension FetchRequestController { public func refresh(using predicate: Predicate<Entity>?, keepOriginalPredicate: Bool) { self.assignPredicate(predicate, keepOriginalPredicate: keepOriginalPredicate) self.refresh() } public func refresh(using rawValue: NSPredicate, keepOriginalPredicate: Bool) { self.assignPredicate(Predicate<Entity>(rawValue: rawValue), keepOriginalPredicate: keepOriginalPredicate) self.refresh() } public func refresh(using sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalSortDescriptors: Bool) { self.assignSortDescriptors(sortDescriptors, keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using rawValues: [NSSortDescriptor], keepOriginalSortDescriptors: Bool) { self.assignSortDescriptors(rawValues.map({ SortDescriptor<Entity>(rawValue: $0) }), keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using predicate: Predicate<Entity>?, sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalPredicate: Bool, keepOriginalSortDescriptors: Bool) { self.assignPredicate(predicate, keepOriginalPredicate: keepOriginalPredicate) self.assignSortDescriptors(sortDescriptors, keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using predicateRawValue: NSPredicate, sortDescriptors sortDescriptorRawValues: [NSSortDescriptor], keepOriginalPredicate: Bool, keepOriginalSortDescriptors: Bool) { self.assignPredicate(Predicate<Entity>(rawValue: predicateRawValue), keepOriginalPredicate: keepOriginalPredicate) self.assignSortDescriptors(sortDescriptorRawValues.map({ SortDescriptor<Entity>(rawValue: $0) }), keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } // public func resetPredicate() { self.refresh(using: self.initialPredicate, keepOriginalPredicate: false) } public func resetSortDescriptors() { self.refresh(using: self.initialSortDescriptors, keepOriginalSortDescriptors: false) } public func resetPredicateAndSortDescriptors() { self.refresh(using: self.initialPredicate, sortDescriptors: self.initialSortDescriptors, keepOriginalPredicate: false, keepOriginalSortDescriptors: false) } } extension FetchRequestController { public func filter(using predicate: Predicate<Entity>) { self.refresh(using: predicate, keepOriginalPredicate: true) } public func filter(using predicateClosure: () -> Predicate<Entity>) { self.refresh(using: predicateClosure(), keepOriginalPredicate: true) } public func filter(using rawValue: NSPredicate) { self.refresh(using: Predicate<Entity>(rawValue: rawValue), keepOriginalPredicate: true) } public func resetFilter() { self.resetPredicate() } public func reset() { self.resetPredicateAndSortDescriptors() } } extension FetchRequestController { fileprivate func assignPredicate(_ predicate: Predicate<Entity>?, keepOriginalPredicate: Bool) { let newPredicate: Predicate<Entity>? if keepOriginalPredicate { if let initialPredicate = self.initialPredicate { if let predicate = predicate { newPredicate = CompoundPredicate<Entity>(type: .and, subpredicates: [initialPredicate, predicate]) } else { newPredicate = initialPredicate } } else { newPredicate = predicate } } else { newPredicate = predicate } self.rawValue.fetchRequest.predicate = newPredicate?.rawValue } fileprivate func assignSortDescriptors(_ sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalSortDescriptors: Bool) { let newSortDescriptors: [SortDescriptor<Entity>]? if keepOriginalSortDescriptors { if let initialSortDescriptors = self.initialSortDescriptors { if let sortDescriptors = sortDescriptors { var tempSortDescriptors = initialSortDescriptors tempSortDescriptors += sortDescriptors newSortDescriptors = tempSortDescriptors } else { newSortDescriptors = initialSortDescriptors } } else { newSortDescriptors = sortDescriptors } } else { newSortDescriptors = sortDescriptors } self.rawValue.fetchRequest.sortDescriptors = newSortDescriptors?.map { $0.rawValue } } }
3aa1eda4c7aa99ab23074ebcbb939a4d
33.547703
211
0.701851
false
false
false
false
ParsifalC/CPCollectionViewKit
refs/heads/master
Demos/CPCollectionViewCircleLayoutDemo/CPCollectionViewCircleLayoutDemo/CPColletionViewCell.swift
mit
1
// // CPColletionViewCell.swift // CPCollectionViewWheelLayout-Swift // // Created by Parsifal on 2016/12/29. // Copyright © 2016年 Parsifal. All rights reserved. // import UIKit class CPCollectionViewCell: UICollectionViewCell { // MARK:- Public Properties public var textLabel:UILabel!; override init(frame: CGRect) { super.init(frame: frame) setupViews(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Private Methods fileprivate func setupViews(frame:CGRect) { contentView.layer.masksToBounds = true contentView.layer.borderColor = UIColor.red.cgColor contentView.layer.borderWidth = 1 let labelFrame = CGRect(x:0, y:0, width:frame.width, height:frame.height) textLabel = UILabel.init(frame: labelFrame) textLabel.font = .systemFont(ofSize: 20) textLabel.textColor = .black textLabel.textAlignment = .center contentView.addSubview(textLabel) } override func layoutSubviews() { super.layoutSubviews() contentView.layer.cornerRadius = bounds.width/2 textLabel.frame = CGRect(x:0, y:0, width:bounds.width, height:bounds.height) } }
72e0c0f167b1df3514cde42e63ec4b8c
28.659091
84
0.65977
false
false
false
false
apple/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/0203-issue-53545.swift
apache-2.0
2
// RUN: not %target-swift-frontend -typecheck %s // https://github.com/apple/swift/issues/53545 enum S<Value> { @propertyWrapper private struct A { var s:UInt = 0 var wrappedValue:Value { didSet { } } init(wrappedValue:Value) { self.wrappedValue = wrappedValue } } @propertyWrapper final class B { @A var wrappedValue:Value var projectedValue:S<Value>.B { self } init(wrappedValue:Value) { self.wrappedValue = wrappedValue } } @propertyWrapper struct O { private var s:UInt? = nil @B private(set) var wrappedValue:Value var a:Bool { self.s.map{ $0 != self.$wrappedValue.wrappedValue.sequence } ?? true } } }
ae8daf8f60c188d1c4e671fa12f74276
17.75
74
0.593333
false
false
false
false
Boilertalk/VaporFacebookBot
refs/heads/master
Sources/VaporFacebookBot/Webhooks/FacebookMessaging.swift
mit
1
// // FacebookMessaging.swift // VaporFacebookBot // // Created by Koray Koska on 24/05/2017. // // import Foundation import Vapor public final class FacebookMessaging: JSONConvertible { // TODO: Support other callback formats public var messageReceived: FacebookMessageReceived? public var postbackReceived: FacebookPostbackReceived? public init(json: JSON) throws { if let _ = json["message"] { messageReceived = try FacebookMessageReceived(json: json) } else if let _ = json["postback"] { postbackReceived = try FacebookPostbackReceived(json: json) } } public func makeJSON() throws -> JSON { let json = JSON() if let j = messageReceived { return try j.makeJSON() } else if let j = postbackReceived { return try j.makeJSON() } return json } }
c07dca8ba9d895feb1b9ab3d30a5ee2f
23.216216
71
0.627232
false
false
false
false
Reggian/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUControlPoint.swift
mit
1
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal typealias SecureDFUProgressCallback = (_ bytesReceived:Int) -> Void internal enum SecureDFUOpCode : UInt8 { case createObject = 0x01 case setPRNValue = 0x02 case calculateChecksum = 0x03 case execute = 0x04 case readError = 0x05 case readObjectInfo = 0x06 case responseCode = 0x60 var code:UInt8 { return rawValue } var description: String{ switch self { case .createObject: return "Create Object" case .setPRNValue: return "Set PRN Value" case .calculateChecksum: return "Calculate Checksum" case .execute: return "Execute" case .readError: return "Read Error" case .readObjectInfo: return "Read Object Info" case .responseCode: return "Response Code" } } } internal enum SecureDFUProcedureType : UInt8 { case command = 0x01 case data = 0x02 var description: String{ switch self{ case .command: return "Command" case .data: return "Data" } } } internal enum SecureDFURequest { case createData(size : UInt32) case createCommand(size : UInt32) case readError() case readObjectInfoCommand() case readObjectInfoData() case setPacketReceiptNotification(value : UInt16) case calculateChecksumCommand() case executeCommand() var data : Data { switch self { case .createData(let aSize): //Split to UInt8 let byteArray = stride(from: 24, through: 0, by: -8).map { UInt8(truncatingBitPattern: aSize >> UInt32($0)) } //Size is converted to Little Endian (0123 -> 3210) let bytes:[UInt8] = [UInt8(SecureDFUOpCode.createObject.code), UInt8(SecureDFUProcedureType.data.rawValue), byteArray[3], byteArray[2], byteArray[1], byteArray[0]] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .createCommand(let aSize): //Split to UInt8 let byteArray = stride(from: 24, through: 0, by: -8).map { UInt8(truncatingBitPattern: aSize >> UInt32($0)) } //Size is converted to Little Endian (0123 -> 3210) let bytes:[UInt8] = [UInt8(SecureDFUOpCode.createObject.code), UInt8(SecureDFUProcedureType.command.rawValue), byteArray[3], byteArray[2], byteArray[1], byteArray[0]] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .readError(): let bytes:[UInt8] = [SecureDFUOpCode.readError.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .readObjectInfoCommand(): let bytes:[UInt8] = [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.command.rawValue] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .readObjectInfoData(): let bytes:[UInt8] = [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.data.rawValue] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .setPacketReceiptNotification(let aSize): let byteArary:[UInt8] = [UInt8(aSize>>8), UInt8(aSize & 0x00FF)] let bytes:[UInt8] = [UInt8(SecureDFUOpCode.setPRNValue.code), byteArary[1], byteArary[0]] return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) case .calculateChecksumCommand(): let byteArray:[UInt8] = [UInt8(SecureDFUOpCode.calculateChecksum.code)] return Data(bytes: UnsafePointer<UInt8>(byteArray), count: byteArray.count) case .executeCommand(): let byteArray:[UInt8] = [UInt8(SecureDFUOpCode.execute.code)] return Data(bytes: UnsafePointer<UInt8>(byteArray), count: byteArray.count) } } var description : String { switch self { case .createData(let size): return "Create object data with size : \(size)" case .createCommand(let size): return "Create object command with size: \(size)" case .readObjectInfoCommand(): return "Read object information command" case .readObjectInfoData(): return "Read object information data" case .setPacketReceiptNotification(let size): return "Packet Receipt Notification command with value: \(size)" case .calculateChecksumCommand(): return "Calculate checksum for last object" case .executeCommand(): return "Execute last object command" case .readError(): return "Read Extended error command" } } } internal enum SecureDFUResultCode : UInt8 { case invalidCode = 0x0 case success = 0x01 case opCodeNotSupported = 0x02 case invalidParameter = 0x03 case insufficientResources = 0x04 case invalidObjcet = 0x05 case signatureMismatch = 0x06 case unsupportedType = 0x07 case operationNotpermitted = 0x08 case operationFailed = 0x0A case extendedError = 0x0B var description:String { switch self { case .invalidCode: return "Invalid code" case .success: return "Success" case .opCodeNotSupported: return "Operation not supported" case .invalidParameter: return "Invalid parameter" case .insufficientResources: return "Insufficient resources" case .invalidObjcet: return "Invalid object" case .signatureMismatch: return "Signature mismatch" case .operationNotpermitted: return "Operation not permitted" case .unsupportedType: return "Unsupported type" case .operationFailed: return "Operation failed" case .extendedError: return "Extended error" } } var code:UInt8 { return rawValue } } internal struct SecureDFUResponse { let opCode:SecureDFUOpCode? let requestOpCode:SecureDFUOpCode? let status:SecureDFUResultCode? var responseData : Data? init?(_ data:Data) { var opCode :UInt8 = 0 var requestOpCode :UInt8 = 0 var status :UInt8 = 0 (data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1)) (data as NSData).getBytes(&requestOpCode, range: NSRange(location: 1, length: 1)) (data as NSData).getBytes(&status, range: NSRange(location: 2, length: 1)) self.opCode = SecureDFUOpCode(rawValue: opCode) self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode) self.status = SecureDFUResultCode(rawValue: status) if data.count > 3 { self.responseData = data.subdata(in: 3..<data.count) }else{ self.responseData = nil } if self.opCode != SecureDFUOpCode.responseCode || self.requestOpCode == nil || self.status == nil { return nil } } var description:String { return "Response (Op Code = \(requestOpCode!.description), Status = \(status!.description))" } } internal struct SecureDFUPacketReceiptNotification { let opCode : SecureDFUOpCode? let requestOpCode : SecureDFUOpCode? let resultCode : SecureDFUResultCode? let offset : Int let crc : UInt32 init?(_ data:Data) { var opCode : UInt8 = 0 var requestOpCode : UInt8 = 0 var resultCode : UInt8 = 0 (data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1)) (data as NSData).getBytes(&requestOpCode, range: NSRange(location: 1, length: 1)) (data as NSData).getBytes(&resultCode, range: NSRange(location: 2, length: 1)) self.opCode = SecureDFUOpCode(rawValue: opCode) self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode) self.resultCode = SecureDFUResultCode(rawValue: resultCode) if self.opCode != SecureDFUOpCode.responseCode { print("wrong opcode \(self.opCode?.description)") return nil } if self.requestOpCode != SecureDFUOpCode.calculateChecksum { print("wrong request code \(self.requestOpCode?.description)") return nil } if self.resultCode != SecureDFUResultCode.success { print("Failed with eror: \(self.resultCode?.description)") return nil } var reportedOffsetLE:[UInt8] = [UInt8](repeating: 0, count: 4) (data as NSData).getBytes(&reportedOffsetLE, range: NSRange(location: 3, length: 4)) let offsetResult: UInt32 = reportedOffsetLE.reversed().reduce(UInt32(0)) { $0 << 0o10 + UInt32($1) } self.offset = Int(offsetResult) var reportedCRCLE:[UInt8] = [UInt8](repeating: 0, count: 4) (data as NSData).getBytes(&reportedCRCLE, range: NSRange(location: 4, length: 4)) let crcResult: UInt32 = reportedCRCLE.reversed().reduce(UInt32(0)) { $0 << 0o10 + UInt32($1) } self.crc = UInt32(crcResult) } } internal class SecureDFUControlPoint : NSObject, CBPeripheralDelegate { static let UUID = CBUUID(string: "8EC90001-F315-4F60-9FB8-838830DAEA50") static func matches(_ characteristic:CBCharacteristic) -> Bool { return characteristic.uuid.isEqual(UUID) } fileprivate var characteristic:CBCharacteristic fileprivate var logger:LoggerHelper fileprivate var success : SDFUCallback? fileprivate var proceed : SecureDFUProgressCallback? fileprivate var report : SDFUErrorCallback? fileprivate var request : SecureDFURequest? fileprivate var uploadStartTime : CFAbsoluteTime? var valid:Bool { return characteristic.properties.isSuperset(of: [CBCharacteristicProperties.write, CBCharacteristicProperties.notify]) } // MARK: - Initialization init(_ characteristic:CBCharacteristic, _ logger:LoggerHelper) { self.characteristic = characteristic self.logger = logger } func getValue() -> Data? { return characteristic.value } func uploadFinished() { self.proceed = nil } // MARK: - Characteristic API methods /** Enables notifications for the DFU ControlPoint characteristics. Reports success or an error using callbacks. - parameter success: method called when notifications were successfully enabled - parameter report: method called in case of an error */ func enableNotifications(onSuccess success:SDFUCallback?, onError report:SDFUErrorCallback?) { // Save callbacks self.success = success self.report = report // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self logger.v("Enabling notifiactions for \(DFUControlPoint.UUID.uuidString)...") logger.d("peripheral.setNotifyValue(true, forCharacteristic: \(DFUControlPoint.UUID.uuidString))") peripheral.setNotifyValue(true, for: characteristic) } func send(_ request:SecureDFURequest, onSuccess success:SDFUCallback?, onError report:SDFUErrorCallback?) { // Save callbacks and parameter self.success = success self.report = report self.request = request // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self switch request { case .createData(let size): logger.a("Writing \(request.description), \(size/8) bytes") break case .createCommand(let size): logger.a("Writing \(request.description), \(size/8) bytes") break case .setPacketReceiptNotification(let size): logger.a("Writing \(request.description), \(size) packets") break default: logger.a("Writing \(request.description)...") break } logger.v("Writing to characteristic \(SecureDFUControlPoint.UUID.uuidString)...") logger.d("peripheral.writeValue(0x\(request.data.hexString), forCharacteristic: \(SecureDFUControlPoint.UUID.uuidString), type: WithResponse)") peripheral.writeValue(request.data, for: characteristic, type: CBCharacteristicWriteType.withResponse) } func waitUntilUploadComplete(onSuccess success:SDFUCallback?, onPacketReceiptNofitication proceed:SecureDFUProgressCallback?, onError report:SDFUErrorCallback?) { // Save callbacks. The proceed callback will be called periodically whenever a packet receipt notification is received. It resumes uploading. self.success = success self.proceed = proceed self.report = report self.uploadStartTime = CFAbsoluteTimeGetCurrent() // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self logger.a("Uploading firmware...") logger.v("Sending firmware DFU Packet characteristic...") } // MARK: - Peripheral Delegate callbacks func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if error != nil { logger.e("Enabling notifications failed") logger.e(error!) report?(SecureDFUError.enablingControlPointFailed, "Enabling notifications failed") } else { logger.v("Notifications enabled for \(SecureDFUControlPoint.UUID.uuidString)") logger.a("DFU Control Point notifications enabled") success?(nil) } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { if error != nil { } else { } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard error == nil else { // This characteristic is never read, the error may only pop up when notification is received logger.e("Receiving notification failed") logger.e(error!) report?(SecureDFUError.receivingNotificationFailed, SecureDFUError.receivingNotificationFailed.description) return } // During the upload we may get either a Packet Receipt Notification, or a Response with status code if proceed != nil { if let prn = SecureDFUPacketReceiptNotification(characteristic.value!) { proceed!(prn.offset) return } } //Otherwise... proceed = nil logger.i("Notification received from \(characteristic.uuid.uuidString), value (0x):\(characteristic.value!.hexString)") // Parse response received let response = SecureDFUResponse(characteristic.value!) if let response = response { logger.a("\(response.description) received") if response.status == SecureDFUResultCode.success { switch response.requestOpCode! { case .readObjectInfo: success?(response.responseData) break case .createObject: success?(response.responseData) break case .setPRNValue: success?(response.responseData) break case .calculateChecksum: success?(response.responseData) break case .readError: success?(response.responseData) break case .execute: success?(nil) break default: success?(nil) break } } else { logger.e("Error \(response.status?.description): \(response.status?.description)") report?(SecureDFUError(rawValue: Int(response.status!.rawValue))!, response.status!.description) } } else { logger.e("Unknown response received: 0x\(characteristic.value!.hexString)") report?(SecureDFUError.unsupportedResponse, SecureDFUError.unsupportedResponse.description) } } }
53d98ca99f82f35bda5ebf61250c20aa
41.372727
178
0.627172
false
false
false
false
jkolb/Jasoom
refs/heads/master
Carthage/Checkouts/Jasoom/JasoomTests/JasoomTests.swift
mit
2
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.net // // 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 Jasoom class JasoomTests: XCTestCase { func testParseEmptyObject() { let string = "{}" do { let json = try JSON.parseString(string) XCTAssert(json.isObject, "Expecting an object") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseEmptyArray() { let string = "[]" do { let json = try JSON.parseString(string) XCTAssert(json.isArray, "Expecting an array") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseNull() { let string = "null" do { let json = try JSON.parseString(string, options: [.AllowFragments]) XCTAssert(json.isNull, "Expecting null") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseTrue() { let string = "true" do { let json = try JSON.parseString(string, options: [.AllowFragments]) XCTAssert(json.isNumber, "Expecting number") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseFalse() { let string = "false" do { let json = try JSON.parseString(string, options: [.AllowFragments]) XCTAssert(json.isNumber, "Expecting number") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseInteger() { let string = "100" do { let json = try JSON.parseString(string, options: [.AllowFragments]) XCTAssert(json.isNumber, "Expecting number") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseFloatingPoint() { let string = "100.12" do { let json = try JSON.parseString(string, options: [.AllowFragments]) XCTAssert(json.isNumber, "Expecting number") } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseBasicObject() { let string = "{\"a\":\"string\",\"b\":100.12,\"c\":true,\"d\":[],\"e\":{}}" do { let json = try JSON.parseString(string) XCTAssert(json["a"].isString, "Expecting a string") XCTAssert(json["b"].isNumber, "Expecting a number") XCTAssert(json["c"].isNumber, "Expecting a number") XCTAssert(json["d"].isArray, "Expecting an array") XCTAssert(json["e"].isObject, "Expecting an object") XCTAssertEqual(json["a"].stringValue, "string") XCTAssertEqual(json["b"].doubleValue, 100.12) XCTAssertEqual(json["c"].boolValue, true) XCTAssertEqual(json["d"].arrayValue, NSArray()) XCTAssertEqual(json["e"].objectValue, NSDictionary()) } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testParseComplexObject() { let string = "{\"a\":{\"a1\":1},\"b\":[1]}" do { let json = try JSON.parseString(string) XCTAssert(json["a"]["a1"].isNumber, "Expecting a number") XCTAssert(json["b"][0].isNumber, "Expecting a number") XCTAssertEqual(json["a"]["a1"].intValue, 1) XCTAssertEqual(json["b"][0].intValue, 1) } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testMissingNameAndIndex() { let string = "{\"a\":{\"a1\":1},\"b\":[1]}" do { let json = try JSON.parseString(string) XCTAssert(json["c"].isUndefined, "Expecting undefined") XCTAssert(json["z"].isUndefined, "Expecting undefined") XCTAssert(json["c"]["z"].isUndefined, "Expecting undefined") XCTAssert(json["z"][10].isUndefined, "Expecting undefined") XCTAssertEqual(json["c"].undefinedValue ?? [], ["c"]) XCTAssertEqual(json["z"].undefinedValue ?? [], ["z"]) XCTAssertEqual(json["c"]["z"].undefinedValue ?? [], ["c", "z"]) XCTAssertEqual(json["z"][10].undefinedValue ?? [], ["z", "10"]) } catch { XCTAssert(false, "Unable to parse: \(string)") } } func testCreateObject() { var object = JSON.objectWithCapacity(5) object["a"] = .String("test") object["b"] = .Number(100) object["c"] = JSON.object() object["c"]["c0"] = .Number(true) object["d"] = JSON.array() object["d"][0] = .String("test") object["d"].append(.Number(1)) object["e"] = .Object(["e0": false]) XCTAssertEqual(object["a"].stringValue, "test") XCTAssertEqual(object["b"].intValue, 100) XCTAssertTrue(object["c"].isObject) XCTAssertEqual(object["c"]["c0"].boolValue, true) XCTAssertTrue(object["d"].isArray) XCTAssertEqual(object["d"][0].stringValue, "test") XCTAssertEqual(object["d"][1].intValue, 1) XCTAssertEqual(object["e"]["e0"].boolValue, false) } func testCreateArrayWithElements() { var array = JSON.arrayWithElements(["test", 100, false]) XCTAssertEqual(array[0].stringValue, "test") XCTAssertEqual(array[1].intValue, 100) XCTAssertEqual(array[2].boolValue, false) } func testCreateObjectWithNameValues() { var object = JSON.objectWithNameValues(["a": "test", "b": 100, "c": false]) XCTAssertEqual(object["a"].stringValue, "test") XCTAssertEqual(object["b"].intValue, 100) XCTAssertEqual(object["c"].boolValue, false) } func testGenerateString() { let object = JSON.objectWithNameValues(["a": "test", "b": 100, "c": false]) do { let string = try object.generateString() XCTAssertEqual(string, "{\"a\":\"test\",\"b\":100,\"c\":false}") } catch { XCTAssert(false, "Unable to generate string: \(object)") } } }
5406b818ebfcb85a11a92155a8d71967
33.953488
83
0.557418
false
true
false
false
1457792186/JWSwift
refs/heads/dev
05-filtering-operators/starter/RxSwiftPlayground/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift
apache-2.0
132
// // TakeUntil.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func takeUntil<O: ObservableType>(_ other: O) -> Observable<E> { return TakeUntil(source: asObservable(), other: other.asObservable()) } } final fileprivate class TakeUntilSinkOther<Other, O: ObserverType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias Parent = TakeUntilSink<Other, O> typealias E = Other fileprivate let _parent: Parent var _lock: RecursiveLock { return _parent._lock } fileprivate let _subscription = SingleAssignmentDisposable() init(parent: Parent) { _parent = parent #if TRACE_RESOURCES let _ = Resources.incrementTotal() #endif } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(.completed) _parent.dispose() case .error(let e): _parent.forwardOn(.error(e)) _parent.dispose() case .completed: _subscription.dispose() } } #if TRACE_RESOURCES deinit { let _ = Resources.decrementTotal() } #endif } final fileprivate class TakeUntilSink<Other, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType { typealias E = O.E typealias Parent = TakeUntil<E, Other> fileprivate let _parent: Parent let _lock = RecursiveLock() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: forwardOn(event) case .error: forwardOn(event) dispose() case .completed: forwardOn(event) dispose() } } func run() -> Disposable { let otherObserver = TakeUntilSinkOther(parent: self) let otherSubscription = _parent._other.subscribe(otherObserver) otherObserver._subscription.setDisposable(otherSubscription) let sourceSubscription = _parent._source.subscribe(self) return Disposables.create(sourceSubscription, otherObserver._subscription) } } final fileprivate class TakeUntil<Element, Other>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _other: Observable<Other> init(source: Observable<Element>, other: Observable<Other>) { _source = source _other = other } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
377e437c6cff9ee684e547fd6781df2f
27.328244
153
0.632444
false
false
false
false
samuelclay/NewsBlur
refs/heads/master
clients/ios/Classes/HorizontalPageViewController.swift
mit
1
// // HorizontalPageViewController.swift // NewsBlur // // Created by David Sinclair on 2020-08-27. // Copyright © 2020 NewsBlur. All rights reserved. // import UIKit // NOTE: This isn't currently used, but may be for #1351 (gestures in vertical scrolling). ///// Manages horizontal story pages. An instance of this is contained within `DetailViewController`. //class HorizontalPageViewController: UIPageViewController { // /// Weak reference to owning detail view controller. // weak var detailViewController: DetailViewController? // // /// The currently displayed vertical page view controller. Call `setCurrentController(_:direction:animated:completion:)` instead to animate to the page. Shouldn't be `nil`, but could be if not set up yet. // var currentController: VerticalPageViewController? { // get { // return viewControllers?.first as? VerticalPageViewController // } // set { // if let viewController = newValue { // setCurrentController(viewController) // } // } // } // // /// The previous vertical page view controller, if it has been requested, otherwise `nil`. // var previousController: VerticalPageViewController? // // /// The next vertical page view controller, if it has been requested, otherwise `nil`. // var nextController: VerticalPageViewController? // // /// Clear the previous and next vertical page view controllers. // func reset() { // previousController = nil // nextController = nil // } // // /// Sets the currently displayed vertical page view controller. // /// // /// - Parameter controller: The vertical page view controller to display. // /// - Parameter direction: The navigation direction. Defaults to `.forward`. // /// - Parameter animated: Whether or not to animate it. Defaults to `false`. // /// - Parameter completion: A closure to call when the animation completes. Defaults to `nil`. // func setCurrentController(_ controller: VerticalPageViewController, direction: UIPageViewController.NavigationDirection = .forward, animated: Bool = false, completion: ((Bool) -> Void)? = nil) { // setViewControllers([controller], direction: direction, animated: animated, completion: completion) // } // // override func setViewControllers(_ viewControllers: [UIViewController]?, direction: UIPageViewController.NavigationDirection, animated: Bool, completion: ((Bool) -> Void)? = nil) { // guard self.viewControllers != viewControllers else { // print("HorizontalPageViewController setViewControllers: \(String(describing: viewControllers)), ignoring as already set") // return // } // // reset() // // print("HorizontalPageViewController setViewControllers: \(String(describing: viewControllers)), current: \(String(describing: self.viewControllers))") // // super.setViewControllers(viewControllers, direction: direction, animated: animated, completion: completion) // } //}
3d17c85761cd384bc13ced3a05415f39
45.121212
210
0.688896
false
false
false
false
Workpop/meteor-ios
refs/heads/master
Examples/Todos/Todos/AppDelegate.swift
mit
1
// Copyright (c) 2014-2015 Martijn Walraven // // 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 CoreData import Meteor let Meteor = METCoreDataDDPClient(serverURL: NSURL(string: "wss://meteor-ios-todos.meteor.com/websocket")) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Meteor.connect() let splitViewController = self.window!.rootViewController as UISplitViewController splitViewController.preferredDisplayMode = .AllVisible splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController let listViewController = masterNavigationController.topViewController as ListsViewController listViewController.managedObjectContext = Meteor.mainQueueManagedObjectContext return true } // MARK: - UISplitViewControllerDelegate func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let todosViewController = (secondaryViewController as? UINavigationController)?.topViewController as? TodosViewController { if todosViewController.listID == nil { return true } } return false } }
0721d88fd3324a0704fee0dd0cc70364
44.696429
222
0.784291
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/SharedExtensions.swift
mit
1
// // Arrays.swift // TeacherTools // // Created by Parker Rushton on 10/30/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit import Marshal extension Bundle { var releaseVersionNumber: String? { return infoDictionary?["CFBundleShortVersionString"] as? String } var buildVersionNumber: String? { return infoDictionary?["CFBundleVersion"] as? String } } extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key == String, Self.Value == Any { func parsedObjects<T: Identifiable>() -> [T] { guard let json = self as? JSONObject else { return [] } let keys = Array(json.keys) let objects: [JSONObject] = keys.compactMap { try? json.value(for: $0) } return objects.compactMap { try? T(object: $0) } } } extension Optional where Wrapped: MarshaledObject { func parsedObjects<T: Identifiable>() -> [T] { guard let json = self as? JSONObject else { return [] } let keys = Array(json.keys) let objects: [JSONObject] = keys.compactMap { try? json.value(for: $0) } return objects.compactMap { try? T(object: $0) } } } extension Array where Iterator.Element == Game { var record: TeamRecord { let wasWonBools = self.compactMap { $0.wasWon } let winCount = wasWonBools.filter { $0 == true }.count let lostCount = wasWonBools.filter { $0 == false }.count return TeamRecord(gamesWon: winCount, gamesLost: lostCount) } } extension Array where Iterator.Element == AtBat { func withResult(_ code: AtBatCode) -> [AtBat] { return filter { $0.resultCode == code } } func withResults(_ codes: [AtBatCode]) -> [AtBat] { return filter { codes.contains($0.resultCode) } } var hitCount: Int { return self.filter { $0.resultCode.isHit }.count } var battingAverageCount: Int { return self.filter { $0.resultCode.countsForBA }.count } var sluggingCount: Double { return reduce(0, { $0 + $1.sluggingValue }) } } extension UUID { func userFacingCode() -> String { let unacceptableCharacters = CharacterSet(charactersIn: "0Oo1IiLl") let strippedString = self.uuidString.trimmingCharacters(in: unacceptableCharacters) return strippedString.last4 } } extension String { subscript(i: Int) -> Character { return self[index(startIndex, offsetBy: i)] } subscript(i: Int) -> String { return String(self[i] as Character) } // subscript(r: Range<Int>) -> String { // let start = index(startIndex, offsetBy: r.lowerBound) // let end = index(startIndex, offsetBy: r.upperBound - r.lowerBound) // return String(self[Range(start ..< end)]) // } var firstLetter: String { return self[0] } var last4: String { return String(suffix(4)) } var isValidEmail: Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } var isValidPhoneNumber: Bool { do { let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)) if let res = matches.first { return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count } else { return false } } catch { return false } } var digits: String { return components(separatedBy: CharacterSet.decimalDigits.inverted).joined() } static var seasonSuggestion: String { let currentMonth = Calendar.current.component(.month, from: Date()) let currentYear = Calendar.current.component(.year, from: Date()) var season = "" switch currentMonth { case 0...5: season = "Spring" case 6...8: season = "Summer" case 9...12: season = "Fall" default: break } return "\(season) \(currentYear)" } // var jerseyNumberFontString: NSAttributedString { // let nsSelf = self as NSString // let firstRange = nsSelf.localizedStandardRange(of: "(") // let secondRange = nsSelf.localizedStandardRange(of: ")") // guard firstRange.length == 1 && secondRange.length == 1 else { return NSAttributedString(string: self) } // // let length = secondRange.location - (firstRange.location + 1) // guard length > 0 else { return NSAttributedString(string: self) } // let numbersRange = NSRange(location: firstRange.location + 1, length: length) // let attributedString = NSMutableAttributedString(string: self) // attributedString.addAttributes([: FontType.jersey.font(withSize: 22)], range: numbersRange) // // return attributedString // } } extension Double { var displayString: String { return String(format: "%.3f", self) } } extension Array { func step(from: Index, to:Index, interval: Int = 1) -> Array<Element> { let strde = stride(from: from, to: to, by: interval) var arr = Array<Element>() for i in strde { arr.append(self[i]) } return arr } func randomElement() -> Element? { guard self.count > 0 else { return nil } let randomIndex = Int.random(0..<self.count) return self[randomIndex] } } extension Int { static func random(_ range: Range<Int>) -> Int { return range.lowerBound + (Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))) } var randomDigitsString: String { guard self > 0 else { return "" } var digitsString = "" for _ in 0..<self { let newDigit = Int(arc4random_uniform(9)) digitsString += String(newDigit) } return digitsString } var doubleValue: Double { return Double(self) } } extension Sequence where Iterator.Element == StringLiteralType { func marshaled() -> JSONObject { var json = JSONObject() for value in self { json[value] = true } return json } func marshaledArray() -> JSONObject { var json = JSONObject() for (index, value) in enumerated() { json["\(index)"] = value } return json } } extension UIViewController { var embededInNavigationController: UINavigationController { return UINavigationController(rootViewController: self) } } extension UIView { func rotate(duration: CFTimeInterval = 2, count: Float = Float.greatestFiniteMagnitude) { let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.toValue = CGFloat.pi * 2 rotation.duration = duration rotation.isCumulative = true rotation.repeatCount = count layer.add(rotation, forKey: "rotationAnimation") } func fadeTransition(duration:CFTimeInterval) { let animation:CATransition = CATransition() animation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) animation.type = kCATransitionFade animation.duration = duration layer.add(animation, forKey: kCATransitionFade) } }
0cbf651b681c4ae0fb54b3cc15923d07
27.899254
114
0.6
false
false
false
false
noahjanderson/PitchPerfect
refs/heads/master
PitchPerfect/PitchPerfect/RecordSoundsViewController.swift
gpl-2.0
1
// // RecordSoundsViewController.swift // PitchPerfect // // Created by Noah J Anderson on 7/23/15. // Copyright (c) 2015 Noah J Anderson. All rights reserved. // import UIKit import AVFoundation class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var stopBtn: UIButton! @IBOutlet weak var recordBtn: UIButton! @IBOutlet weak var recordingLabel: UILabel! var audioRecorder: AVAudioRecorder! var audioSession: AVAudioSession! var soundFile: NSURL! var errorRecorder: NSError? var recordedAudio: RecordedAudio! override func viewDidLoad() { super.viewDidLoad() audioSession = AVAudioSession.sharedInstance() audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) audioSession.setActive(true, error: nil) let docsDir: AnyObject = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] let soundFilePath = docsDir.stringByAppendingPathComponent("recordedAudio.caf") soundFile = NSURL.fileURLWithPath(soundFilePath as String) var recordSettings = [AVFormatIDKey: kAudioFormatAppleIMA4, AVSampleRateKey:44100.0, AVNumberOfChannelsKey:2, AVEncoderBitRateKey:12800.0, AVLinearPCMBitDepthKey:16, AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue ] audioRecorder = AVAudioRecorder(URL: soundFile, settings: recordSettings as [NSObject : AnyObject], error: &errorRecorder) audioRecorder.delegate = self audioRecorder.meteringEnabled = true audioRecorder.prepareToRecord() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) recordBtn.enabled = true stopBtn.hidden = true recordingLabel.text = "Tap to Record" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "StoppedRecording"){ let playSoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController let data = sender as! RecordedAudio playSoundsVC.receivedAudio = data } } @IBAction func recordAudio(sender: UIButton) { recordBtn.enabled = false stopBtn.hidden = false recordingLabel.text = "Recording" audioRecorder.record() } @IBAction func stopRecording(sender: UIButton) { audioRecorder.stop() } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool){ if (flag){ recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent!, filePathUrl: recorder.url) performSegueWithIdentifier("StoppedRecording", sender: recordedAudio) } else{ println("Some Error in Recording") } } }
aafb049f185ed4d147e1802655c8d84c
34.120879
157
0.677409
false
false
false
false
BlurredSoftware/BSWInterfaceKit
refs/heads/develop
Sources/BSWInterfaceKit/Extensions/Keyboard+LayoutGuide.swift
mit
1
// // Keyboard+LayoutGuide.swift // KeyboardLayoutGuide // // Created by Sacha DSO on 14/11/2017. // Copyright © 2017 freshos. All rights reserved. // #if canImport(UIKit) import UIKit private class Keyboard { static let shared = Keyboard() var currentHeight: CGFloat = 0 } public extension UIView { private struct AssociatedKeys { static var keyboardLayoutGuide = "keyboardLayoutGuide" } /// A layout guide representing the inset for the keyboard. /// Use this layout guide’s top anchor to create constraints pinning to the top of the keyboard. var bswKeyboardLayoutGuide: UILayoutGuide { get { #if targetEnvironment(macCatalyst) return self.safeAreaLayoutGuide #else return self.getCustomKeybardLayoutGuide() #endif } } private func getCustomKeybardLayoutGuide() -> UILayoutGuide { if let obj = objc_getAssociatedObject(self, &AssociatedKeys.keyboardLayoutGuide) as? KeyboardLayoutGuide { return obj } let new = KeyboardLayoutGuide() addLayoutGuide(new) new.setUp() objc_setAssociatedObject(self, &AssociatedKeys.keyboardLayoutGuide, new as Any, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return new } } @available(macCatalyst, unavailable) open class KeyboardLayoutGuide: UILayoutGuide { public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init() { super.init() // Observe keyboardWillChangeFrame notifications let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } internal func setUp() { guard let view = owningView else { return } NSLayoutConstraint.activate([ heightAnchor.constraint(equalToConstant: Keyboard.shared.currentHeight), leftAnchor.constraint(equalTo: view.leftAnchor), rightAnchor.constraint(equalTo: view.rightAnchor), bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } @objc private func keyboardWillChangeFrame(_ note: Notification) { if let height = note.keyboardHeight(onWindow: owningView?.window) { heightConstraint?.constant = height animate(note) Keyboard.shared.currentHeight = height } } private func animate(_ note: Notification) { if isVisible(view: self.owningView!) { self.owningView?.layoutIfNeeded() } else { UIView.performWithoutAnimation { self.owningView?.layoutIfNeeded() } } } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: - Helpers extension UILayoutGuide { internal var heightConstraint: NSLayoutConstraint? { guard let target = owningView else { return nil } for c in target.constraints { if let fi = c.firstItem as? UILayoutGuide, fi == self && c.firstAttribute == .height { return c } } return nil } } extension Notification { @available(macCatalyst, unavailable) func keyboardHeight(onWindow w: UIWindow?) -> CGFloat? { guard let v = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil } // Weirdly enough UIKeyboardFrameEndUserInfoKey doesn't have the same behaviour // in ios 10 or iOS 11 so we can't rely on v.cgRectValue.width let screenHeight = w?.bounds.height ?? UIScreen.main.bounds.height return screenHeight - v.cgRectValue.minY } } // Credits to John Gibb for this nice helper :) // https://stackoverflow.com/questions/1536923/determine-if-uiview-is-visible-to-the-user func isVisible(view: UIView) -> Bool { func isVisible(view: UIView, inView: UIView?) -> Bool { guard let inView = inView else { return true } let viewFrame = inView.convert(view.bounds, from: view) if viewFrame.intersects(inView.bounds) { return isVisible(view: view, inView: inView.superview) } return false } return isVisible(view: view, inView: view.superview) } #endif
5056ce6cc60c4036f3220e25bf838da5
30.524476
123
0.632431
false
false
false
false
apatronl/Left
refs/heads/master
Left/View Controller/ResultsCollectionView.swift
mit
1
// // ResultsCollectionView.swift // Left // // Created by Alejandrina Patron on 7/22/16. // Copyright © 2016 Ale Patrón. All rights reserved. // import Foundation import UIKit import Nuke import SwiftyDrop class ResultsCollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIViewControllerPreviewingDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let favoritesManager = FavoritesManager.shared private var recipesLoader: RecipesLoader? private var recipes = [RecipeItem]() var ingredients = [String]() var addButton: UIBarButtonItem! var manager = Nuke.Manager.shared override func viewDidLoad() { super.viewDidLoad() if (traitCollection.forceTouchCapability == .available) { registerForPreviewing(with: self, sourceView: self.collectionView) } // Add infinite scroll handler collectionView?.addInfiniteScroll { [weak self] (scrollView) -> Void in if let loader = self?.recipesLoader { if loader.hasMoreRecipes() { self?.loadMoreRecipes() { scrollView.finishInfiniteScroll() } } else { print("No more recipes!") scrollView.finishInfiniteScroll() } } } activityIndicator.hidesWhenStopped = true var ingredientsString = "" for ingredient in ingredients { ingredientsString += ingredient + "," } loadRecipes(ingredients: ingredientsString) } // override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // // self.tabBarController?.tabBar.isHidden = false // } // MARK: Collection View Delegate func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recipes.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath as IndexPath) as! RecipeCollectionCell let recipe = recipes[indexPath.row] cell.recipe = recipe // Handle delete button action cell.actionButton.layer.setValue(indexPath.row, forKey: "index") cell.actionButton.addTarget(self, action: #selector(ResultsCollectionView.saveRecipe(sender:)), for: UIControlEvents.touchUpInside) // Handle label tap action let labelTap = UITapGestureRecognizer(target: self, action: #selector(ResultsCollectionView.openRecipeUrl)) labelTap.numberOfTapsRequired = 1 cell.recipeName.addGestureRecognizer(labelTap) // Handle photo tap action let photoTap = UITapGestureRecognizer(target: self, action: #selector(ResultsCollectionView.openRecipeUrl)) photoTap.numberOfTapsRequired = 1 cell.recipePhoto.addGestureRecognizer(photoTap) if recipe.photo == nil { recipe.photoUrl!.urlToImg(completion: { recipePhoto in if let photo = recipePhoto { recipe.photo = photo } else { recipe.photo = UIImage(named: "default") } }) let imageView = cell.recipePhoto let request = Request(url: URL(string: recipe.photoUrl!)!) manager.loadImage(with: request, into: imageView!) } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var height = (UIScreen.main.bounds.width / 2) - 15 if height > 250 { height = (UIScreen.main.bounds.width / 3) - 15 } return CGSize(width: height, height: height) } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let recipeCell = cell as! RecipeCollectionCell //recipeCell.recipePhoto.nk_cancelLoading() manager.cancelRequest(for: recipeCell.recipePhoto) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10, 10, 10, 10) } // MARK: UIViewControllerPreviewingDelegate func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) as? RecipeCollectionCell else { return nil } guard let webView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipeWebView") as? RecipeWebView else { return nil } webView.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil) webView.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "star-navbar"), style: .plain, target: self, action: nil) webView.recipe = cell.recipe webView.preferredContentSize = CGSize(width: 0.0, height: self.view.frame.height * 0.8) let cellAttributes = collectionView.layoutAttributesForItem(at: indexPath) previewingContext.sourceRect = cellAttributes?.frame ?? cell.frame return webView } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } // MARK: Helper func loadRecipes(ingredients: String) { activityIndicator.startAnimating() recipesLoader = RecipesLoader(ingredients: ingredients) recipesLoader!.load(completion: { recipes, error in if let error = error { self.showAlert(alertType: .SearchFailure) self.navigationItem.title = "Error" print("Error! " + error.localizedDescription) } else if (recipes.count == 0) { self.showAlert(alertType: .NoResults) self.recipesLoader!.setHasMore(hasMore: false) self.navigationItem.title = "No Results" } else { // Food2Fork returns at most 30 recipes on each page if (recipes.count < 30) { self.recipesLoader!.setHasMore(hasMore: false) } self.recipes = recipes self.collectionView.reloadData() self.navigationItem.title = "Results" } self.activityIndicator.stopAnimating() }) } private func loadMoreRecipes(handler: ((Void) -> Void)?) { if let loader = recipesLoader { loader.loadMore(completion: { recipes, error in if let error = error { self.handleResponse(data: nil, error: error, completion: handler) } else { self.handleResponse(data: recipes, error: nil, completion: handler) } }) } } // Handle response when loading more recipes with infinite scroll private func handleResponse(data: [RecipeItem]?, error: Error?, completion: ((Void) -> Void)?) { if let _ = error { completion?() return } if (data!.count == 0) { self.recipesLoader?.setHasMore(hasMore: false) completion?() return } // Food2Fork returns at most 30 recipes on each page if (data!.count < 30) { self.recipesLoader?.setHasMore(hasMore: false) } var indexPaths = [NSIndexPath]() let firstIndex = recipes.count for (i, recipe) in data!.enumerated() { let indexPath = NSIndexPath(item: firstIndex + i, section: 0) recipes.append(recipe) indexPaths.append(indexPath) } collectionView?.performBatchUpdates({ () -> Void in (self.collectionView?.insertItems(at: indexPaths as [IndexPath]))! }, completion: { (finished) -> Void in completion?() }); } func saveRecipe(sender: UIButton) { let index: Int = (sender.layer.value(forKey: "index")) as! Int let recipe = recipes[index] favoritesManager.addRecipe(recipe: recipe) Drop.down("Added to your favorites ⭐", state: Custom.Left) // Haptic feedback (available iOS 10+) if #available(iOS 10.0, *) { let savedRecipeFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy) savedRecipeFeedbackGenerator.impactOccurred() } } func openRecipeUrl(sender: UITapGestureRecognizer) { let cell = sender.view?.superview?.superview as! RecipeCollectionCell let webView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipeWebView") as! RecipeWebView webView.recipe = cell.recipe webView.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil) webView.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "star-navbar"), style: .plain, target: self, action: nil) self.navigationController?.pushViewController(webView, animated: true) } }
9bf72233a171b4fc30243f6953f22431
41.134146
175
0.636179
false
false
false
false
pkadams67/PKA-Project---Advent-16
refs/heads/master
Controllers/DayCollectionCell.swift
mit
1
// // DayCollectionCell.swift // Advent '16 // // Created by Paul Kirk Adams on 11/15/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import UIKit class DayCollectionCell: UICollectionViewCell { @IBOutlet var label: UILabel! @IBOutlet var markedView: UIView! @IBOutlet var markedViewWidth: NSLayoutConstraint! @IBOutlet var markedViewHeight: NSLayoutConstraint! var date: Date? { didSet { if date != nil { label.text = "\(date!.day)" } else { label.text = "" } } } var disabled: Bool = false { didSet { if disabled { alpha = 0.25 } else { alpha = 1 } } } var mark: Bool = false { didSet { if mark { markedView!.hidden = false } else { markedView!.hidden = true } } } override func layoutSubviews() { super.layoutSubviews() markedViewWidth!.constant = min(self.frame.width, self.frame.height) markedViewHeight!.constant = min(self.frame.width, self.frame.height) markedView!.layer.cornerRadius = min(self.frame.width, self.frame.height) / 2.0 } }
e8972fb64bb8e9e5276af1f85edea40f
23.555556
87
0.523379
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressShareExtension/ShareExtractor.swift
gpl-2.0
1
import Foundation import MobileCoreServices import UIKit import ZIPFoundation import Down import Aztec /// A type that represents the information we can extract from an extension context /// struct ExtractedShare { var title: String var description: String var url: URL? var selectedText: String var importedText: String var images: [ExtractedImage] var combinedContentHTML: String { var rawLink = "" var readOnText = "" if let url = url { rawLink = url.absoluteString.stringWithAnchoredLinks() let attributionText = NSLocalizedString("Read on", comment: "In the share extension, this is the text used right before attributing a quote to a website. Example: 'Read on www.site.com'. We are looking for the 'Read on' text in this situation.") readOnText = "<br>— \(attributionText) \(rawLink)" } // Build the returned string by doing the following: // * 1: Look for imported text. // * 2: Look for selected text, if it exists put it into a blockquote. // * 3: No selected text, but we have a page description...use that. // * 4: No selected text, but we have a page title...use that. // * Finally, default to a simple link if nothing else is found guard importedText.isEmpty else { return importedText } guard selectedText.isEmpty else { return "<blockquote><p>\(selectedText.escapeHtmlNamedEntities())\(readOnText)</p></blockquote>" } if !description.isEmpty { return "<p>\(description)\(readOnText)</p>" } else if !title.isEmpty { return "<p>\(title)\(readOnText)</p>" } else { return "<p>\(rawLink)</p>" } } } struct ExtractedImage { enum InsertionState { case embeddedInHTML case requiresInsertion } let url: URL var insertionState: InsertionState } /// Extracts valid information from an extension context. /// struct ShareExtractor { let extensionContext: NSExtensionContext init(extensionContext: NSExtensionContext) { self.extensionContext = extensionContext } /// Loads the content asynchronously. /// /// - Important: This method will only call completion if it can successfully extract content. /// - Parameters: /// - completion: the block to be called when the extractor has obtained content. /// func loadShare(completion: @escaping (ExtractedShare) -> Void) { extractText { extractedTextResults in self.extractImages { extractedImages in let title = extractedTextResults?.title ?? "" let description = extractedTextResults?.description ?? "" let selectedText = extractedTextResults?.selectedText ?? "" let importedText = extractedTextResults?.importedText ?? "" let url = extractedTextResults?.url var returnedImages = extractedImages if let extractedImageURLs = extractedTextResults?.images { returnedImages.append(contentsOf: extractedImageURLs) } completion(ExtractedShare(title: title, description: description, url: url, selectedText: selectedText, importedText: importedText, images: returnedImages)) } } } /// Determines if the extractor will be able to obtain valid content from /// the extension context. /// /// This doesn't ensure success though. It will only check that the context /// includes known types, but there might still be errors loading the content. /// var validContent: Bool { return textExtractor != nil || imageExtractor != nil } } // MARK: - Private /// A private type that represents the information we can extract from an extension context /// attachment /// private struct ExtractedItem { /// Any text that was selected /// var selectedText: String? /// Text that was imported from another app /// var importedText: String? /// A description of the resource if available /// var description: String? /// A URL associated with the resource if available /// var url: URL? /// A title of the resource if available /// var title: String? /// An image /// var images = [ExtractedImage]() } private extension ShareExtractor { var supportedTextExtractors: [ExtensionContentExtractor] { return [ SharePostExtractor(), ShareBlogExtractor(), PropertyListExtractor(), URLExtractor(), PlainTextExtractor() ] } var imageExtractor: ExtensionContentExtractor? { return ImageExtractor() } var textExtractor: ExtensionContentExtractor? { return supportedTextExtractors.first(where: { extractor in extractor.canHandle(context: extensionContext) }) } func extractText(completion: @escaping (ExtractedItem?) -> Void) { guard let textExtractor = textExtractor else { completion(nil) return } textExtractor.extract(context: extensionContext) { extractedItems in guard extractedItems.count > 0 else { completion(nil) return } let combinedTitle = extractedItems.compactMap({ $0.title }).joined(separator: " ") let combinedDescription = extractedItems.compactMap({ $0.description }).joined(separator: " ") let combinedSelectedText = extractedItems.compactMap({ $0.selectedText }).joined(separator: "\n\n") let combinedImportedText = extractedItems.compactMap({ $0.importedText }).joined(separator: "\n\n") var extractedImages = [ExtractedImage]() extractedItems.forEach({ item in item.images.forEach({ extractedImage in extractedImages.append(extractedImage) }) }) let urls = extractedItems.compactMap({ $0.url }) completion(ExtractedItem(selectedText: combinedSelectedText, importedText: combinedImportedText, description: combinedDescription, url: urls.first, title: combinedTitle, images: extractedImages)) } } func extractImages(completion: @escaping ([ExtractedImage]) -> Void) { guard let imageExtractor = imageExtractor else { completion([]) return } imageExtractor.extract(context: extensionContext) { extractedItems in guard extractedItems.count > 0 else { completion([]) return } var extractedImages = [ExtractedImage]() extractedItems.forEach({ item in item.images.forEach({ extractedImage in extractedImages.append(extractedImage) }) }) completion(extractedImages) } } } private protocol ExtensionContentExtractor { func canHandle(context: NSExtensionContext) -> Bool func extract(context: NSExtensionContext, completion: @escaping ([ExtractedItem]) -> Void) func saveToSharedContainer(image: UIImage) -> URL? func saveToSharedContainer(wrapper: FileWrapper) -> URL? func copyToSharedContainer(url: URL) -> URL? } private protocol TypeBasedExtensionContentExtractor: ExtensionContentExtractor { associatedtype Payload var acceptedType: String { get } func convert(payload: Payload) -> ExtractedItem? } private extension TypeBasedExtensionContentExtractor { /// Maximum Image Size /// var maximumImageSize: CGSize { let dimension = ShareExtensionService.retrieveShareExtensionMaximumMediaDimension() ?? Constants.defaultMaxDimension return CGSize(width: dimension, height: dimension) } func canHandle(context: NSExtensionContext) -> Bool { return !context.itemProviders(ofType: acceptedType).isEmpty } func extract(context: NSExtensionContext, completion: @escaping ([ExtractedItem]) -> Void) { let itemProviders = context.itemProviders(ofType: acceptedType) print(acceptedType) var results = [ExtractedItem]() guard itemProviders.count > 0 else { DispatchQueue.main.async { completion(results) } return } // There 1 or more valid item providers here, lets work through them let syncGroup = DispatchGroup() for provider in itemProviders { syncGroup.enter() // Remember, this is an async call.... provider.loadItem(forTypeIdentifier: acceptedType, options: nil) { (payload, error) in let payload = payload as? Payload let result = payload.flatMap(self.convert(payload:)) if let result = result { results.append(result) } syncGroup.leave() } } // Call the completion handler after all of the provider items are loaded syncGroup.notify(queue: DispatchQueue.main) { completion(results) } } func saveToSharedContainer(image: UIImage) -> URL? { guard let encodedMedia = image.resizeWithMaximumSize(maximumImageSize)?.JPEGEncoded(), let fullPath = tempPath(for: "jpg") else { return nil } do { try encodedMedia.write(to: fullPath, options: [.atomic]) } catch { DDLogError("Error saving \(fullPath) to shared container: \(String(describing: error))") return nil } return fullPath } func saveToSharedContainer(wrapper: FileWrapper) -> URL? { guard let wrappedFileName = wrapper.filename?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let wrappedURL = URL(string: wrappedFileName), let newPath = tempPath(for: wrappedURL.pathExtension) else { return nil } do { try wrapper.write(to: newPath, options: [], originalContentsURL: nil) } catch { DDLogError("Error saving \(newPath) to shared container: \(String(describing: error))") return nil } return newPath } func copyToSharedContainer(url: URL) -> URL? { guard let newPath = tempPath(for: url.lastPathComponent) else { return nil } do { try FileManager.default.copyItem(at: url, to: newPath) } catch { DDLogError("Error saving \(newPath) to shared container: \(String(describing: error))") return nil } return newPath } private func tempPath(for ext: String) -> URL? { guard let mediaDirectory = ShareMediaFileManager.shared.mediaUploadDirectoryURL else { return nil } let fileName = "image_\(UUID().uuidString).\(ext)".lowercased() return mediaDirectory.appendingPathComponent(fileName) } } private struct URLExtractor: TypeBasedExtensionContentExtractor { typealias Payload = URL let acceptedType = kUTTypeURL as String func convert(payload: URL) -> ExtractedItem? { guard !payload.isFileURL else { return processLocalFile(url: payload) } var returnedItem = ExtractedItem() returnedItem.url = payload return returnedItem } private func processLocalFile(url: URL) -> ExtractedItem? { switch url.pathExtension { case "textbundle": return handleTextBundle(url: url) case "textpack": return handleTextPack(url: url) case "text", "txt": return handlePlainTextFile(url: url) case "md", "markdown": return handleMarkdown(url: url) default: return nil } } private func handleTextPack(url: URL) -> ExtractedItem? { let fileManager = FileManager() guard let temporaryDirectoryURL = try? FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: url, create: true) else { return nil } defer { try? FileManager.default.removeItem(at: temporaryDirectoryURL) } let textBundleURL: URL do { try fileManager.unzipItem(at: url, to: temporaryDirectoryURL) let files = try fileManager.contentsOfDirectory(at: temporaryDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) guard let unzippedBundleURL = files.first(where: { url in url.pathExtension == "textbundle" }) else { return nil } textBundleURL = unzippedBundleURL } catch { DDLogError("TextPack opening failed: \(error.localizedDescription)") return nil } return handleTextBundle(url: textBundleURL) } private func handleTextBundle(url: URL) -> ExtractedItem? { var error: NSError? let bundleWrapper = TextBundleWrapper(contentsOf: url, options: .immediate, error: &error) var returnedItem = ExtractedItem() var cachedImages = [String: ExtractedImage]() bundleWrapper.assetsFileWrapper.fileWrappers?.forEach { (key: String, fileWrapper: FileWrapper) in guard let fileName = fileWrapper.filename else { return } let assetURL = url.appendingPathComponent(fileName, isDirectory: false) switch assetURL.pathExtension.lowercased() { case "heic": autoreleasepool { if let file = fileWrapper.regularFileContents, let tmpImage = UIImage(data: file), let cachedURL = saveToSharedContainer(image: tmpImage) { cachedImages["assets/\(fileName)"] = ExtractedImage(url: cachedURL, insertionState: .requiresInsertion) } } case "jpg", "jpeg", "gif", "png": if let cachedURL = saveToSharedContainer(wrapper: fileWrapper) { cachedImages["assets/\(fileName)"] = ExtractedImage(url: cachedURL, insertionState: .requiresInsertion) } default: break } } if bundleWrapper.type == kUTTypeMarkdown { if let formattedItem = handleMarkdown(md: bundleWrapper.text), var html = formattedItem.importedText { returnedItem = formattedItem for key in cachedImages.keys { if let escapedKey = key.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) { let searchKey = "src=\"\(escapedKey)\"" if html.contains(searchKey), let cachedPath = cachedImages[key]?.url { html = html.replacingOccurrences(of: searchKey, with: "src=\"\(cachedPath.absoluteString)\" \(MediaAttachment.uploadKey)=\"\(cachedPath.lastPathComponent)\"") cachedImages[key]?.insertionState = .embeddedInHTML } } } returnedItem.importedText = html } } else { returnedItem.importedText = bundleWrapper.text.escapeHtmlNamedEntities() } returnedItem.images = Array(cachedImages.values) return returnedItem } private func handlePlainTextFile(url: URL) -> ExtractedItem? { var returnedItem = ExtractedItem() let rawText = (try? String(contentsOf: url)) ?? "" returnedItem.importedText = rawText.escapeHtmlNamedEntities() return returnedItem } private func handleMarkdown(url: URL, item: ExtractedItem? = nil) -> ExtractedItem? { guard let md = try? String(contentsOf: url) else { return item } return handleMarkdown(md: md, item: item) } private func handleMarkdown(md content: String, item: ExtractedItem? = nil) -> ExtractedItem? { var md = content var result: ExtractedItem if let item = item { result = item } else { result = ExtractedItem() } // If the first line is formatted as a heading, use it as the title let lines = md.components(separatedBy: .newlines) if lines.count > 1, lines[0].first == "#" { let mdTitle = lines[0].replacingOccurrences(of: "^#{1,6} ?", with: "", options: .regularExpression) let titleConverter = Down(markdownString: mdTitle) if let title = try? titleConverter.toHTML(.safe) { // remove the wrapping paragraph tags result.title = title.replacingOccurrences(of: "</?p>", with: "", options: .regularExpression) md = lines[1...].joined(separator: "\n") } } // convert the body of the post let converter = Down(markdownString: md) guard let html = try? converter.toHTML(.safe) else { return item } result.importedText = html return result } } private struct ImageExtractor: TypeBasedExtensionContentExtractor { typealias Payload = AnyObject let acceptedType = kUTTypeImage as String func convert(payload: AnyObject) -> ExtractedItem? { var returnedItem = ExtractedItem() switch payload { case let url as URL: if let imageURL = copyToSharedContainer(url: url) { returnedItem.images = [ExtractedImage(url: imageURL, insertionState: .requiresInsertion)] } case let data as Data: if let image = UIImage(data: data), let imageURL = saveToSharedContainer(image: image) { returnedItem.images = [ExtractedImage(url: imageURL, insertionState: .requiresInsertion)] } case let image as UIImage: if let imageURL = saveToSharedContainer(image: image) { returnedItem.images = [ExtractedImage(url: imageURL, insertionState: .requiresInsertion)] } default: break } return returnedItem } } private struct PropertyListExtractor: TypeBasedExtensionContentExtractor { typealias Payload = [String: Any] let acceptedType = kUTTypePropertyList as String func convert(payload: [String: Any]) -> ExtractedItem? { guard let results = payload[NSExtensionJavaScriptPreprocessingResultsKey] as? [String: Any] else { return nil } var returnedItem = ExtractedItem() returnedItem.title = string(in: results, forKey: "title") returnedItem.selectedText = string(in: results, forKey: "selection") returnedItem.description = string(in: results, forKey: "description") if let urlString = string(in: results, forKey: "url") { returnedItem.url = URL(string: urlString) } return returnedItem } func string(in dictionary: [String: Any], forKey key: String) -> String? { guard let value = dictionary[key] as? String, !value.isEmpty else { return nil } return value } } private struct PlainTextExtractor: TypeBasedExtensionContentExtractor { typealias Payload = String let acceptedType = kUTTypePlainText as String func convert(payload: String) -> ExtractedItem? { guard !payload.isEmpty else { return nil } var returnedItem = ExtractedItem() // Often, an attachment type _should_ have a type of "public.url" however in reality // the type will be "public.plain-text" which is why this Extractor is activated. As a fix, // let's use a data detector to determine if the payload text is a link (and check to make sure the // match string is the same length as the payload because the detector could find matches within // the selected text — we just want to make sure shared URLs are handled). let types: NSTextCheckingResult.CheckingType = [.link] let detector = try? NSDataDetector(types: types.rawValue) if let match = detector?.firstMatch(in: payload, options: [], range: NSMakeRange(0, payload.count)), match.resultType == .link, let url = match.url, url.absoluteString.count == payload.count { returnedItem.url = url } else { returnedItem.selectedText = payload } return returnedItem } } private struct SharePostExtractor: TypeBasedExtensionContentExtractor { typealias Payload = Data let acceptedType = SharePost.typeIdentifier func convert(payload: Data) -> ExtractedItem? { guard let post = SharePost(data: payload) else { return nil } var returnedItem = ExtractedItem() returnedItem.title = post.title returnedItem.selectedText = post.content returnedItem.url = post.url returnedItem.description = post.summary return returnedItem } } private struct ShareBlogExtractor: TypeBasedExtensionContentExtractor { typealias Payload = Data let acceptedType = ShareBlog.typeIdentifier func convert(payload: Data) -> ExtractedItem? { guard let post = SharePost(data: payload) else { return nil } var returnedItem = ExtractedItem() returnedItem.title = post.title returnedItem.url = post.url returnedItem.description = post.summary let content: String if let summary = post.summary { content = "\(summary)\n\n" } else { content = "" } returnedItem.selectedText = content return returnedItem } } private enum Constants { static let defaultMaxDimension = 3000 }
73c03d97fff891afe6f76ec65e7706b3
35.133122
246
0.595746
false
false
false
false
AndrewBennet/readinglist
refs/heads/master
ReadingList/ViewControllers/Settings/ViewControllerRepresentable/MFMailComposeView.swift
gpl-3.0
1
import Foundation import SwiftUI import MessageUI struct MailView: UIViewControllerRepresentable { @Binding var isShowing: Bool let receipients: [String]? let messageBody: String? let subject: String? class Coordinator: NSObject, MFMailComposeViewControllerDelegate { @Binding var isShowing: Bool init(isShowing: Binding<Bool>) { _isShowing = isShowing } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { isShowing = false } } func makeCoordinator() -> Coordinator { return Coordinator(isShowing: $isShowing) } func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController { let viewController = MFMailComposeViewController() viewController.mailComposeDelegate = context.coordinator if let messageBody = messageBody { viewController.setMessageBody(messageBody, isHTML: false) } if let subject = subject { viewController.setSubject(subject) } viewController.setToRecipients(receipients) return viewController } func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: UIViewControllerRepresentableContext<MailView>) { } }
3429b179906b49d5c0430b07c37ee227
32.97561
141
0.705671
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/Utility/PingHubManager.swift
gpl-2.0
2
import Foundation import CocoaLumberjack import Reachability // This is added as a top level function to avoid cluttering PingHubManager.init private func defaultAccountToken() -> String? { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) guard let account = service.defaultWordPressComAccount() else { return nil } guard let token = account.authToken, !token.isEmpty else { assertionFailure("Can't create a PingHub client if the account has no auth token") return nil } return token } /// PingHubManager will attempt to keep a PinghubClient connected as long as it /// is alive while certain conditions are met. /// /// # When it connects /// /// The manager will try to connect as long as it has an oAuth2 token and the /// app is in the foreground. /// /// When a connection fails for some reason, it will try to reconnect whenever /// there is an internet connection, as detected by Reachability. If the app /// thinks it's online but connections are still failing, the manager adds an /// increasing delay to the reconnection to avoid too many attempts. /// /// # Debugging /// /// There are a couple helpers to aid with debugging the manager. /// /// First, if you want to see a detailed log of every state changed and the /// resulting action in the console, add `-debugPinghub` to the arguments passed /// on launch in Xcode's scheme editor. /// /// Second, if you want to simulate some network error conditions to test the /// retry algorithm, you can set a breakpoint in any Swift code, and enter into /// the LLDB prompt: /// /// expr PinghubClient.Debug.simulateUnreachableHost(true) /// /// This will simulate a "Unreachable Host" error every time the PingHub client /// tries to connect. If you want to disable it, do the same thing but passing /// `false`. /// class PingHubManager: NSObject { enum Configuration { /// Sequence of increasing delays to apply to the retry mechanism (in seconds) /// static let delaySequence = [1, 2, 5, 15, 30] /// Enables manager during tests /// static let enabledDuringTests = false } fileprivate typealias StatePattern = Pattern<State> fileprivate struct State { // Connected or connecting var connected: Bool var reachable: Bool var foreground: Bool var authToken: String? enum Pattern { static let connected: StatePattern = { $0.connected } static let reachable: StatePattern = { $0.reachable } static let foreground: StatePattern = { $0.foreground } static let loggedIn: StatePattern = { $0.authToken != nil } } } fileprivate var client: PinghubClient? = nil { willSet { client?.disconnect() } } fileprivate let reachability: Reachability = Reachability.forInternetConnection() fileprivate var state: State { didSet { stateChanged(old: oldValue, new: state) } } fileprivate var delay = IncrementalDelay(Configuration.delaySequence) fileprivate var delayedRetry: DispatchDelayedAction? override init() { let foreground = (UIApplication.shared.applicationState != .background) let authToken = defaultAccountToken() state = State(connected: false, reachable: reachability.isReachable(), foreground: foreground, authToken: authToken) super.init() guard enabled else { return } let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(PingHubManager.accountChanged), name: .WPAccountDefaultWordPressComAccountChanged, object: nil) notificationCenter.addObserver(self, selector: #selector(PingHubManager.applicationDidEnterBackground), name: .UIApplicationDidEnterBackground, object: nil) notificationCenter.addObserver(self, selector: #selector(PingHubManager.applicationWillEnterForeground), name: .UIApplicationWillEnterForeground, object: nil) if let token = authToken { client = client(token: token) // Simulate state change to figure out if we should try to connect stateChanged(old: state, new: state) } setupReachability() } deinit { delayedRetry?.cancel() reachability.stopNotifier() NotificationCenter.default.removeObserver(self) } fileprivate func stateChanged(old: State, new: State) { let connected = State.Pattern.connected let disconnected = !connected let foreground = State.Pattern.foreground let loggedIn = State.Pattern.loggedIn let reachable = State.Pattern.reachable let connectionAllowed = loggedIn & foreground let connectionNotAllowed = !connectionAllowed let reconnectable = reachable & foreground & loggedIn func debugLog(_ message: String) { Debug.logStateChange(from: old, to: new, message: message) } switch (old, new) { case (_, connected & !connectionAllowed): debugLog("disconnect") disconnect() case (disconnected, disconnected & reconnectable): debugLog("reconnect") delay.reset() connect() case (connected, disconnected & reconnectable): debugLog("reconnect delayed (\(delay.current)s)") connectDelayed() case (connectionNotAllowed, disconnected & connectionAllowed): debugLog("connect") connect() default: debugLog("nothing to do") break } } fileprivate func client(token: String) -> PinghubClient { let client = PinghubClient(token: token) client.delegate = self return client } private var enabled: Bool { return !UIApplication.shared.isRunningTestSuite() || Configuration.enabledDuringTests } } // MARK: - Inputs fileprivate extension PingHubManager { // MARK: loggedIn @objc func accountChanged() { let authToken = defaultAccountToken() client = authToken.map({ client(token: $0 ) }) // we set a new state as we are changing two properties and only want to trigger didSet once state = State(connected: false, reachable: state.reachable, foreground: state.foreground, authToken: authToken) } // MARK: foreground @objc func applicationDidEnterBackground() { state.foreground = false } @objc func applicationWillEnterForeground() { state.foreground = true } // MARK: reachability func setupReachability() { let reachabilityChanged: (Reachability?) -> Void = { [weak self] reachability in guard let manager = self, let reachability = reachability else { return } manager.state.reachable = reachability.isReachable() } reachability.reachableBlock = reachabilityChanged reachability.unreachableBlock = reachabilityChanged reachability.startNotifier() } } // MARK: - Actions fileprivate extension PingHubManager { func connect() { guard !state.connected else { return } state.connected = true DDLogInfo("PingHub connecting") client?.connect() } func connectDelayed() { delayedRetry = DispatchDelayedAction(delay: .seconds(delay.current)) { [weak self] in self?.connect() } delay.increment() } func disconnect() { delayedRetry?.cancel() DDLogInfo("PingHub disconnecting") client?.disconnect() state.connected = false } } extension PingHubManager: PinghubClientDelegate { func pingubDidConnect(_ client: PinghubClient) { DDLogInfo("PingHub connected") delay.reset() state.connected = true // Trigger a full sync, since we might have missed notes while PingHub was disconnected NotificationSyncMediator()?.sync() } func pinghubDidDisconnect(_ client: PinghubClient, error: Error?) { if let error = error { DDLogError("PingHub disconnected: \(error)") } else { DDLogInfo("PingHub disconnected") } state.connected = false } func pinghub(_ client: PinghubClient, actionReceived action: PinghubClient.Action) { guard let mediator = NotificationSyncMediator() else { return } switch action { case .delete(let noteID): DDLogInfo("PingHub delete, syncing note \(noteID)") mediator.deleteNote(noteID: String(noteID)) case .push(let noteID, _, _, _): DDLogInfo("PingHub push, syncing note \(noteID)") mediator.syncNote(with: String(noteID), completion: { _ in }) } } func pinghub(_ client: PinghubClient, unexpected message: PinghubClient.Unexpected) { DDLogError(message.description) } } extension PingHubManager { // Functions to aid debugging. // It might not be my prettiest code, but it is meant to be ephemeral like a rainbow. fileprivate enum Debug { static func diff(_ lhs: State, _ rhs: State) -> String { func b(_ b: Bool) -> String { return b ? "Y" : "N" } var diff = [String]() if lhs.connected != rhs.connected { diff.append("conn: \(b(lhs.connected)) -> \(b(rhs.connected))") } else { diff.append("conn: \(b(rhs.connected))") } if lhs.reachable != rhs.reachable { diff.append("reach: \(b(lhs.reachable)) -> \(b(rhs.reachable))") } else { diff.append("reach: \(b(rhs.reachable))") } if lhs.foreground != rhs.foreground { diff.append("fg: \(b(lhs.foreground)) -> \(b(rhs.foreground))") } else { diff.append("fg: \(b(rhs.foreground))") } if lhs.authToken != rhs.authToken { diff.append("log: \(b(lhs.authToken != nil)) -> \(b(rhs.authToken != nil)))") } else { diff.append("log: \(b(rhs.authToken != nil))") } return "(" + diff.joined(separator: ", ") + ")" } static func logStateChange(from old: State, to new: State, message: String) { // To enable debugging, add `-debugPinghub` to the launch arguments // in Xcode's scheme editor guard CommandLine.arguments.contains("-debugPinghub") else { return } let diffMessage = diff(old, new) DDLogInfo("PingHub state changed \(diffMessage), \(message)") } } }
296d9171a260beb34b11f8cfa8fd3f0e
33.948882
166
0.623914
false
false
false
false
iot-spotted/spotted
refs/heads/master
AppMessage/AppMessage/DataObjects/Game.swift
bsd-3-clause
1
// // Game.swift // AppMessage // // Created by Robert Maratos on 2/22/17. // Copyright © 2017 mirabeau. All rights reserved. // // // Message.swift // // Created by Edwin Vermeer on 01-07-14. // Copyright (c) 2014 EVICT BV. All rights reserved. // // SwiftLint ignore variable_name import CloudKit import EVReflection let BECOMING_IT_SCORE = 10 let CORRECT_VOTE_SCORE = 1 let INCORRECT_VOTE_SCORE = -2 let YES_VOTE_LIMIT = 1 let NO_VOTE_LIMIT = 1 enum VoteStatusEnum: String { case InProgress = "I", Pass = "P", Fail = "F" } class GameUser: CKDataObject { var User_ID: String = "" var Name: String = "" var Score: Int = 0 } class GroupState: CKDataObject { var Group_ID: String = "" var It_User_ID: String = "" var It_User_Name: String = "" } class Vote: CKDataObject { var Group_ID: String = "" var It_User_ID: String = "" var It_User_Name: String = "" var Sender_User_ID: String = "" var Sender_Name: String = "" var Asset_ID: String = "" var Status: String = VoteStatusEnum.InProgress.rawValue var Yes: Int = 0 var No: Int = 0 } class UserVote: CKDataObject { var User_ID: String = "" var Vote_ID: String = "" var Yes: Bool = false }
2348d04ea7b1f8c9b975beb08a098119
19.295082
59
0.62601
false
false
false
false
gnachman/iTerm2
refs/heads/master
sources/ParsedSSHArguments.swift
gpl-2.0
2
// // ParsedSSHArguments.swift // iTerm2SharedARC // // Created by George Nachman on 5/12/22. // import Foundation import FileProviderService struct ParsedSSHArguments: Codable, CustomDebugStringConvertible { let hostname: String let username: String? let port: Int? private(set) var paramArgs = ParamArgs() private(set) var commandArgs = [String]() var debugDescription: String { return "recognized params: \(paramArgs.debugDescription); username=\(String(describing: username)); hostname=\(hostname); port=\(String(describing: port)); command=\(commandArgs.joined(separator: ", "))" } struct ParamArgs: Codable, OptionSet, CustomDebugStringConvertible { var rawValue: Set<OptionValue> enum Option: String, Codable { case loginName = "l" case port = "p" } struct OptionValue: Codable, Equatable, Hashable { let option: Option let value: String } init?(_ option: String, value: String) { guard let opt = Option(rawValue: option) else { return nil } rawValue = Set([OptionValue(option: opt, value: value)]) } init() { rawValue = Set<OptionValue>() } init(rawValue: Set<OptionValue>) { self.rawValue = rawValue } typealias RawValue = Set<OptionValue> mutating func formUnion(_ other: __owned ParsedSSHArguments.ParamArgs) { rawValue.formUnion(other.rawValue) } mutating func formIntersection(_ other: ParsedSSHArguments.ParamArgs) { rawValue.formIntersection(other.rawValue) } mutating func formSymmetricDifference(_ other: __owned ParsedSSHArguments.ParamArgs) { rawValue.formSymmetricDifference(other.rawValue) } func hasOption(_ option: Option) -> Bool { return rawValue.contains { ov in ov.option == option } } func value(for option: Option) -> String? { return rawValue.first { ov in ov.option == option }?.value } var debugDescription: String { return rawValue.map { "-\($0.option.rawValue) \($0.value)" }.sorted().joined(separator: " ") } } var identity: SSHIdentity { return SSHIdentity(hostname, username: username, port: port ?? 22) } init(_ string: String, booleanArgs boolArgsString: String) { let booleanArgs = Set(Array<String.Element>(boolArgsString).map { String($0) }) guard let args = (string as NSString).componentsInShellCommand() else { hostname = "" username = nil port = nil return } var destination: String? = nil var optionsAllowed = true var preferredUser: String? = nil var preferredPort: Int? = nil var i = 0 while i < args.count { defer { i += 1 } let arg = args[i] if destination != nil && !arg.hasPrefix("-") { // ssh localhost /bin/bash // ^^^^^^^^^ // parsing this arg. After this point arguments are to /bin/bash, not to ssh client. // Note that in "ssh localhost -t /bin/bash", "-t" is an argument to the ssh client. optionsAllowed = false } if optionsAllowed && arg.hasPrefix("-") { if arg == "--" { optionsAllowed = false continue } let splitArg = Array(arg) if splitArg.count == 1 { // Invalid argument of "-" continue } if splitArg.dropFirst().contains(where: { booleanArgs.contains(String($0)) }) { // Is boolean arg, ignore. continue } if Array(arg).count != 2 { // All unrecognized single-letter args I guess continue } i += 1 if i >= args.count { // Missing param. Just ignore it. continue } guard let paramArg = ParamArgs(String(arg.dropFirst()), value: args[i]) else { continue } paramArgs.formUnion(paramArg) continue } if destination == nil { if let url = URL(string: arg), url.scheme == "ssh" { if let user = url.user, let host = url.host { preferredUser = user destination = host } else if let host = url.host { destination = host } if !paramArgs.hasOption(.port), let urlPort = url.port { preferredPort = urlPort } } destination = arg continue } commandArgs.append(arg) } // ssh's behavior seems to be to glue arguments together with spaces and reparse them. // ["ssh", "example.com", "cat", "file with space"] executes ["cat", "file", "with", "space"] // ["ssh", "example.com", "cat", "'file with space"'] executes ["cat", "file with space"] commandArgs = (commandArgs.joined(separator: " ") as NSString).componentsInShellCommand() hostname = destination ?? "" username = preferredUser ?? paramArgs.value(for: .loginName) port = preferredPort ?? paramArgs.value(for: .port).map { Int($0) } ?? 22 } }
4812e04a7c3016780c71f46b17a3c0e6
34.084337
211
0.513049
false
false
false
false
GuoMingJian/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Home/View/RecommendGameView.swift
mit
1
// // RecommendGameView.swift // DYZB // // Created by 郭明健 on 2017/11/16. // Copyright © 2017年 com.joy.www. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMarg : CGFloat = 10 class RecommendGameView: UIView { //MARK:- 定义数据属性 var groups : [BaseGameModel]? { didSet { //刷新表格 collectionView.reloadData() } } //MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! //MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin] //注册Cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) //给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMarg, bottom: 0, right: kEdgeInsetMarg) } } //MARK:- 快速创建View的类方法 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } //MARK:- 遵守UICollectionView数据源协议 extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell let group = groups![indexPath.item] cell.baseGameModel = group return cell } }
8d9dcfc3f1cd87b995ea3c7e10c33245
27.575758
126
0.664369
false
false
false
false
bcylin/QuickTableViewController
refs/heads/develop
Source/Model/RadioSection.swift
mit
1
// // RadioSection.swift // QuickTableViewController // // Created by Ben on 17/08/2017. // Copyright © 2017 bcylin. // // 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 /// A section that allows only one option selected in a table view. open class RadioSection: Section { // MARK: - Initializer /// Initializes a section with a title, containing rows and an optional footer. public init(title: String?, options: [OptionRowCompatible], footer: String? = nil) { self.options = options super.init(title: title, rows: [], footer: footer) } private override init(title: String?, rows: [Row & RowStyle], footer: String? = nil) { fatalError("init with title, rows, and footer is not supported") } // MARK: - Section /// The array of rows in the section. open override var rows: [Row & RowStyle] { get { return options } set { options = newValue as? [OptionRowCompatible] ?? options } } // MARK: - RadioSection /// A boolean that indicates whether there's always one option selected. open var alwaysSelectsOneOption: Bool = false { didSet { if alwaysSelectsOneOption && selectedOption == nil { options.first?.isSelected = true } } } /// The array of options in the section. It's identical to the `rows`. open private(set) var options: [OptionRowCompatible] /// Returns the selected index, or nil when nothing is selected. open var indexOfSelectedOption: Int? { return options.firstIndex { $0.isSelected } } /// Returns the selected option row, or nil when nothing is selected. open var selectedOption: OptionRowCompatible? { if let index = indexOfSelectedOption { return options[index] } else { return nil } } /// Toggle the selection of the given option and keep options mutually exclusive. /// If `alwaysSelectOneOption` is set to true, it will not deselect the current selection. /// /// - Parameter option: The option to flip the `isSelected` state. /// - Returns: The indexes of changed options. open func toggle(_ option: OptionRowCompatible) -> IndexSet { if option.isSelected && alwaysSelectsOneOption { return [] } defer { option.isSelected = !option.isSelected } if option.isSelected { // Deselect the selected option. return options.firstIndex(where: { $0 === option }).map { [$0] } ?? [] } var toggledIndexes: IndexSet = [] for (index, element) in options.enumerated() { switch element { case let target where target === option: toggledIndexes.insert(index) case _ where element.isSelected: toggledIndexes.insert(index) element.isSelected = false default: break } } return toggledIndexes } }
dedbd0fb2f0a57477586087402d45abe
31.15
92
0.684292
false
false
false
false
BlenderSleuth/Unlokit
refs/heads/master
Unlokit/Nodes/BackButtonNode.swift
gpl-3.0
1
// // BackButtonNode.swift // Unlokit // // Created by Ben Sutherland on 1/2/17. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit class BackButtonNode: SKSpriteNode { // MARK: Variable // Initialised as implicitly-unwrapped optionals for file archive compatability var label: SKLabelNode! var redCircle: SKShapeNode! var blueCircle: SKShapeNode! var pressed = false // Must be initalised from scene weak var delegate: LevelController! // Used for initialising from file required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) redCircle = SKShapeNode(circleOfRadius: size.width / 2) redCircle.fillColor = .red redCircle.strokeColor = .red redCircle.alpha = 0.2 blueCircle = SKShapeNode(circleOfRadius: size.width / 2) blueCircle.fillColor = .blue blueCircle.strokeColor = .blue blueCircle.isHidden = true label = SKLabelNode(text: "Back") label.position = CGPoint(x: 40, y: -40) label.fontName = neuropolFont label.fontSize = 26 label.zPosition = 10 self.position = position addChild(redCircle) addChild(blueCircle) addChild(label) isUserInteractionEnabled = true } private func press() { pressed = !pressed redCircle.isHidden = pressed blueCircle.isHidden = !pressed } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { press() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { press() delegate.returnToLevelSelect() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { press() } }
dfb7a58eb6b099dd334d47bb255a57ae
23.492754
80
0.720118
false
false
false
false
TENDIGI/Obsidian-UI-iOS
refs/heads/master
src/CameraView.swift
mit
1
// // CameraView.swift // Alfredo // // Created by Eric Kunz on 8/24/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation @IBDesignable class CameraView: UIView { let topBarHeight = CGFloat(50) let captureButtonDimension = CGFloat(20) var closeButton: UIButton! var titleLabel: UILabel! var cameraPreview: UIView! var libraryButton: UIButton! var captureButton: UIButton! @IBInspectable var flashButton: UIButton! var switchCameraButton: UIButton! var imageReview: UIImageView! // var questionLabel: UILabel! var reviewContainerView: UIView! // var acceptButton: UIButton! // var rejectButtton: UIButton! override init(frame: CGRect) { super.init(frame: frame) // Use constraints to have buttons between bottom of frame and camera preview but no less than maybe 10 from the bottom backgroundColor = UIColor.black let rect = frame let topBar = UIView(frame: CGRect(x: 0, y: 0, width: Int(rect.width), height: Int(topBarHeight))) closeButton = CloseCross(frame: CGRect(x: 5, y: 5, width: topBarHeight - 5, height: topBarHeight - 5)) titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: rect.width, height: topBarHeight)) titleLabel.text = "Camera" topBar.addSubview(closeButton) topBar.addSubview(titleLabel) addSubview(topBar) cameraPreview = UIView(frame: rect) cameraPreview.backgroundColor = UIColor.darkGray addSubview(cameraPreview) let bottomSpace = CGFloat(10) captureButton = CaptureButton(frame: CGRect(x: rect.width / 2 - captureButtonDimension, y: rect.height - (captureButtonDimension + bottomSpace), width: captureButtonDimension, height: captureButtonDimension)) addSubview(captureButton) let sideButtonDimension = CGFloat(15) flashButton = UIButton(frame: CGRect(x: rect.width * 0.75 - sideButtonDimension / 2.0, y: rect.height - (sideButtonDimension + bottomSpace), width: sideButtonDimension, height: sideButtonDimension)) addSubview(flashButton) libraryButton = UIButton(frame: CGRect(x: rect.width * 0.25 - sideButtonDimension, y: rect.height - (sideButtonDimension + bottomSpace), width: sideButtonDimension, height: sideButtonDimension)) addSubview(libraryButton) imageReview = UIImageView(frame: cameraPreview.frame) imageReview.isHidden = true addSubview(imageReview) reviewContainerView = UIView(frame: CGRect(x: 0, y: topBarHeight + rect.width, width: rect.width, height: rect.height - topBarHeight + rect.width)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CloseCross: UIButton { @IBInspectable var color = UIColor.white @IBInspectable var lineWidth = 5 override func draw(_ rect: CGRect) { let pathOne = UIBezierPath() pathOne.move(to: CGPoint(x: 0, y: 0)) pathOne.addLine(to: CGPoint(x: rect.width, y: rect.height)) pathOne.move(to: CGPoint(x: rect.width, y: 0)) pathOne.addLine(to: CGPoint(x: 0, y: rect.height)) let shapeLayer = CAShapeLayer() shapeLayer.path = pathOne.cgPath shapeLayer.lineWidth = CGFloat(lineWidth) shapeLayer.fillColor = color.cgColor } } @IBDesignable class CaptureButton: UIButton { @IBInspectable var color = UIColor.clear @IBInspectable var borderColor = UIColor.white @IBInspectable var borderWidth = CGFloat(2) override func draw(_ rect: CGRect) { var buttonRect: CGRect if isSelected { buttonRect = CGRect(x: 0, y: 0, width: rect.size.width * 0.9, height: rect.size.height * 0.9) } else { buttonRect = CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height) } let button = UIView(frame: buttonRect) button.makeCircular() button.applyBorder(borderWidth, color: borderColor) } }
9559ec6388b7e8303065018ec2e98310
37.066038
216
0.67658
false
false
false
false
Ivacker/swift
refs/heads/master
test/SILGen/errors.swift
apache-2.0
7
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify %s | FileCheck %s import Swift class Cat {} enum HomeworkError : ErrorType { case TooHard case TooMuch case CatAteIt(Cat) } // CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error ErrorType) { // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error ErrorType) { // CHECK: [[BOX:%.*]] = alloc_existential_box $ErrorType, $HomeworkError // CHECK: [[T0:%.*]] = function_ref @_TFO6errors13HomeworkError7TooHardFMS0_S0_ : $@convention(thin) (@thin HomeworkError.Type) -> @owned HomeworkError // CHECK-NEXT: [[T1:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: store [[T2]] to [[BOX]]#1 // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]]#0 func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@out T, @in T) -> @error ErrorType { // CHECK: [[BOX:%.*]] = alloc_existential_box $ErrorType, $HomeworkError // CHECK: [[T0:%.*]] = function_ref @_TFO6errors13HomeworkError7TooMuchFMS0_S0_ : $@convention(thin) (@thin HomeworkError.Type) -> @owned HomeworkError // CHECK-NEXT: [[T1:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: store [[T2]] to [[BOX]]#1 // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]]#0 func dont_return<T>(argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} : // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [[ARG_TEMP]]#1 // CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]]#1, [[ARG_TEMP]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: [[T0:%.*]] = load [[RET_TEMP]]#1 : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[ARG_TEMP]]#0 // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $ErrorType // CHECK-NEXT: store [[ERROR]] to [[SRC_TEMP]]#1 // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success ErrorType in [[SRC_TEMP]]#1 : $*ErrorType to HomeworkError in [[DEST_TEMP]]#1 : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0:%.*]] = load [[DEST_TEMP]]#1 : $*HomeworkError // CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: destroy_addr [[SRC_TEMP]]#1 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[RETURN]]([[T0]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: strong_release [[ERROR]] : $ErrorType // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) // CHECK: [[DR_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) func all_together_now(flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $HasThrowingInit // CHECK-NEXT: assign %0 to [[T1]] : $*Int // CHECK-NEXT: return [[T0]] : $HasThrowingInit // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(thin) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error ErrorType) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] enum ColorError : ErrorType { case Red, Green, Blue } //CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32 //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32 //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error ErrorType // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: throw [[T0]] : $ErrorType struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error ErrorType { // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*DoomedClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $DoomedClass, #DoomedClass.check!1 : DoomedClass -> () throws -> () , $@convention(method) (@guaranteed DoomedClass) -> @error ErrorType // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: strong_release [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: strong_release [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: throw [[T0]] : $ErrorType class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*HappyStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*HappyClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : HappyClass -> () -> () , $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: strong_release [[SELF]] : $HappyClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(fn: () throws -> T) throws -> T { return try fn() } func testThunk(fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs9ErrorType__XFo__iSizoPS___ : $@convention(thin) (@out Int, @owned @callee_owned () -> (Int, @error ErrorType)) -> @error ErrorType // CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error ErrorType)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: throw [[T0]] : $ErrorType func createInt(fn: () -> Int) throws {} func testForceTry(fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> () // CHECK: [[T0:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error ErrorType // CHECK: try_apply [[T0]](%0) // CHECK: strong_release // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]] // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]] // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: strong_release [[VALUE_2]] : $Cat // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $ErrorType) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error ErrorType) // CHECK: %0 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error ErrorType) // CHECK: try_apply %0() : $@convention(thin) () -> (CatFood, @error ErrorType), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : $ErrorType) // CHECK: throw [[ERROR]] : $ErrorType // Throwing statements inside cases. func getHungryCat(food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error ErrorType) // CHECK: bb0(%0 : $CatFood): // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : $ErrorType): // CHECK: br bb8([[ERROR:%.*]] : $ErrorType) // CHECK: bb7([[ERROR:%.*]] : $ErrorType): // CHECK: br bb8([[ERROR]] : $ErrorType) // CHECK: bb8([[ERROR:%.*]] : $ErrorType): // CHECK: throw [[ERROR]] : $ErrorType func take_many_cats(cats: Cat...) throws {} func test_variadic(cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ // CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error ErrorType // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[ARRAY:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat): // CHECK-NEXT: store [[CAT0]] to [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: strong_retain %0 // CHECK-NEXT: store %0 to [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat): // CHECK-NEXT: store [[CAT2]] to [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat): // CHECK-NEXT: store [[CAT3]] to [[ELT3]] // Complete the call and return. // CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error ErrorType, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: strong_release %0 : $Cat // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $ErrorType) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: strong_release %0 : $Cat // CHECK-NEXT: throw [[ERROR]] // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error ErrorType) // CHECK: [[BOX:%.*]] = alloc_box $BaseThrowingInit // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]#1 // Initialize subField. // CHECK: [[T0:%.*]] = load [[MARKED_BOX]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: assign %1 to [[T1]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load [[MARKED_BOX]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK-NEXT: function_ref // CHECK-NEXT: [[T3:%.*]] = function_ref @_TFC6errors15HasThrowingInitc // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { typealias Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(inout b: B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable, B.Structure : Supportable> (@inout B) -> @error ErrorType { // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]]#1 : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B, B.Structure>([[BUFFER_CAST]], [[MATBUFFER]]#1, [[BASE:%.*#1]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*B.Structure // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] func supportStructure<B: Buildable>(inout b: B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @_TF6errors16supportStructure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: retain_value [[INDEX:%1]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]]#1 : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B, B.Structure>([[BUFFER_CAST]], [[MATBUFFER]]#1, [[INDEX]], [[BASE:%.*#1]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*B.Structure // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: release_value [[INDEX]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: release_value [[INDEX]] : $String // CHECK: throw [[ERROR]] struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(inout b: Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: retain_value [[INDEX]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load [[B:%2#1]] : $*Bridge // CHECK-NEXT: retain_value [[BASE]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX]], [[BASE]]) // CHECK-NEXT: release_value [[BASE]] // CHECK-NEXT: store [[T0]] to [[TEMP]]#1 // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]#1) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]]#1 // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX]], [[B]]) // CHECK-NEXT: dealloc_stack [[TEMP]]#0 // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]]#1 // CHECK-NEXT: retain_value [[T0]] // CHECK-NEXT: retain_value [[INDEX]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX]], [[B]]) // CHECK-NEXT: destroy_addr [[TEMP]]#1 // CHECK-NEXT: dealloc_stack [[TEMP]]#0 // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] struct OwnedBridge { var owner : Builtin.UnknownObject subscript(name: String) -> Pylon { addressWithOwner { return (nil, owner) } mutableAddressWithOwner { return (nil, owner) } } } func supportStructure(inout b: OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[INDEX]], [[BASE:%2#1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_release [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: strong_release [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (nil, owner) } mutableAddressWithPinnedNativeOwner { return (nil, owner) } } } func supportStructure(inout b: PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[INDEX]], [[BASE:%2#1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: retain_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: release_value [[OWNER]] // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.Some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>): // CHECK-NEXT: release_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTry() { _ = try? make_a_cat() } // CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_ // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $Optional<Cat> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: store [[VALUE]] to [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.Some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]]#1 : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]]#1 : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]]#0 : $*@local_storage Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryAddressOnly<T>(obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]]#1 : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryAddressOnlyVar<T>(obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_ // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]] // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]] // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.Some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>): // CHECK-NEXT: release_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_ // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.Some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: {{^}$}} func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_ // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $Optional<()> // CHECK-NEXT: = init_enum_data_addr [[BOX]]#1 : $*Optional<()>, #Optional.Some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<()>, #Optional.Some!enumelt.1 // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<()> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'unit' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]]#1 : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]]#0 : $*@local_storage Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsAddressOnly<T>(obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsAddressOnlyVar<T>(obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} }
97aa917acaf09bafbd473eb0f89e52d3
46.598163
238
0.606566
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
refs/heads/main
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/PanoramaViewController.swift
apache-2.0
1
// Copyright 2020 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 GoogleMaps import UIKit class PanoramaViewController: UIViewController { private let markerLocation = CLLocationCoordinate2D(latitude: 40.761455, longitude: -73.977814) private var panoramaView = GMSPanoramaView(frame: .zero) private var statusLabel = UILabel(frame: .zero) private var configured = false override func loadView() { navigationController?.navigationBar.isTranslucent = false panoramaView.moveNearCoordinate(.newYork) panoramaView.backgroundColor = .gray panoramaView.delegate = self view = panoramaView statusLabel.alpha = 0.0 statusLabel.backgroundColor = .blue statusLabel.textColor = .white statusLabel.textAlignment = .center view.addSubview(statusLabel) statusLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ statusLabel.topAnchor.constraint(equalTo: view.topAnchor), statusLabel.heightAnchor.constraint(equalToConstant: 30), statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) } } extension PanoramaViewController: GMSPanoramaViewDelegate { func panoramaView(_ panoramaView: GMSPanoramaView, didMove camera: GMSPanoramaCamera) { print("Camera:\(camera.orientation.heading), \(camera.orientation.pitch), \(camera.zoom)") } func panoramaView(_ view: GMSPanoramaView, didMoveTo panorama: GMSPanorama?) { if configured { return } let marker = GMSMarker(position: markerLocation) marker.icon = GMSMarker.markerImage(with: .purple) marker.panoramaView = panoramaView let heading = GMSGeometryHeading(.newYork, markerLocation) panoramaView.camera = GMSPanoramaCamera(heading: heading, pitch: 0, zoom: 1) configured = true } func panoramaViewDidStartRendering(_ panoramaView: GMSPanoramaView) { statusLabel.alpha = 0.8 statusLabel.text = "Rendering" } func panoramaViewDidFinishRendering(_ panoramaView: GMSPanoramaView) { statusLabel.alpha = 0 } }
dfe6f2b08c8e0728fe63a82c176240a6
37.492754
97
0.756024
false
false
false
false
coderMONSTER/iosstar
refs/heads/master
iOSStar/AppAPI/HttpRequest/AppAPIHelper.swift
gpl-3.0
1
// // AppAPIHelper.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation class AppAPIHelper: NSObject { fileprivate static var _loginApi = LoginSocketApi() fileprivate static var _friendApi = UserSocketApi() fileprivate static var _newsApi = NewsSocketAPI() fileprivate static var _marketAPI = MarketSocketAPI() fileprivate static var _dealAPI = DealSocketAPI() class func login() -> LoginApi{ return _loginApi } class func user() -> UserApi{ return _friendApi } class func newsApi()-> NewsApi { return _newsApi } class func marketAPI()-> MarketAPI{ return _marketAPI } class func dealAPI()-> DealAPI { return _dealAPI } }
bfcb6cee9eec8f04a06c0bde203dfc2a
20.615385
59
0.627521
false
false
false
false
superk589/ZKDrawerController
refs/heads/master
Sources/ZKDrawerController.swift
mit
1
// // ZKDrawerController.swift // ZKDrawerController // // Created by zzk on 2017/1/7. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit public protocol ZKDrawerControllerDelegate: class { func drawerController(_ drawerVC: ZKDrawerController, willShow vc: UIViewController) func drawerController(_ drawerVC: ZKDrawerController, didHide vc: UIViewController) } public extension UIViewController { var drawerController: ZKDrawerController? { var vc = parent while vc != nil { if vc is ZKDrawerController { return vc as? ZKDrawerController } else { vc = vc?.parent } } return nil } } open class ZKDrawerController: UIViewController, ZKDrawerCoverViewDelegate { public enum Style { /// side controller covers the main controller, shadows the edge of side controllers' view case plain /// side controller inserts below the main controller, shadows the edge of main controller's view case cover /// side controller lays beside the main controller case insert } public enum Position { case left case right case center } override open var childForStatusBarHidden: UIViewController? { return centerViewController } open override var childForStatusBarStyle: UIViewController? { return centerViewController } open var defaultRightWidth: CGFloat = 300 { didSet { if let view = rightViewController?.view { view.snp.updateConstraints({ (update) in update.width.equalTo(defaultRightWidth) }) rightWidth = defaultRightWidth } } } open var defaultLeftWidth: CGFloat = 300 { didSet { if let view = leftViewController?.view { view.snp.updateConstraints({ (update) in update.width.equalTo(defaultLeftWidth) }) leftWidth = defaultLeftWidth } } } /// 作为容器的滚动视图 open var containerView: ZKDrawerScrollView! /// 背景图片视图 open var backgroundImageView: UIImageView! /// 左侧阴影 var leftShadowView: ZKDrawerShadowView! /// 右侧阴影 var rightShadowView: ZKDrawerShadowView! /// 主视图蒙层 open var mainCoverView: ZKDrawerCoverView! private var isTransitioning = false /// 阴影视图的宽度 open var shadowWidth: CGFloat = 5 { didSet { leftShadowView.snp.updateConstraints { (update) in update.width.equalTo(shadowWidth) } rightShadowView.snp.updateConstraints { (update) in update.width.equalTo(shadowWidth) } } } /// 主视图控制器 open var centerViewController: UIViewController! { didSet { remove(vc: oldValue) setupMainViewController(centerViewController) } } /// 右侧抽屉视图控制器 open var rightViewController: UIViewController? { didSet { remove(vc: oldValue) setupRightViewController(rightViewController) } } /// 左侧抽屉视图控制器 open var leftViewController: UIViewController? { didSet { remove(vc: oldValue) setupLeftViewController(leftViewController) } } open func viewController(of position: Position) -> UIViewController? { switch position { case .center: return centerViewController case .left: return leftViewController case .right: return rightViewController } } /// 主视图在抽屉出现后的缩放比例 open var mainScale: CGFloat = 1 var lastPosition: Position = .center open weak var delegate: ZKDrawerControllerDelegate? public init(center: UIViewController, right: UIViewController? = nil, left: UIViewController? = nil) { super.init(nibName: nil, bundle: nil) containerView = ZKDrawerScrollView() backgroundImageView = UIImageView() containerView.addSubview(backgroundImageView) backgroundImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } view.addSubview(containerView) containerView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } containerView.delegate = self centerViewController = center rightViewController = right leftViewController = left setupMainViewController(center) setupLeftViewController(left) setupRightViewController(right) mainCoverView = ZKDrawerCoverView() center.view.addSubview(mainCoverView) mainCoverView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } mainCoverView.alpha = 0 mainCoverView.delegate = self leftShadowView = ZKDrawerShadowView() leftShadowView.direction = .right containerView.addSubview(leftShadowView) leftShadowView.snp.makeConstraints { (make) in make.right.equalTo(center.view) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } rightShadowView = ZKDrawerShadowView() rightShadowView.direction = .left containerView.addSubview(rightShadowView) rightShadowView.snp.makeConstraints { (make) in make.left.equalTo(center.view) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } leftShadowView.alpha = 0 rightShadowView.alpha = 0 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let position = currentPosition isTransitioning = true coordinator.animate(alongsideTransition: { (context) in switch position { case .right: self.containerView.setNeedsAdjustTo(.right) case .center: self.containerView.setNeedsAdjustTo(.center) case .left: self.containerView.setNeedsAdjustTo(.left) } self.containerView.setNeedsLayout() self.containerView.layoutIfNeeded() self.updateTransforms() }, completion: { finished in self.isTransitioning = false }) } /// default true, set navigation pop gesture's priority higher than drawer controller's gesture open var shouldRequireFailureOfNavigationPopGesture: Bool { get { return containerView.shouldRequireFailureOfNavigationPopGesture } set { containerView.shouldRequireFailureOfNavigationPopGesture = newValue } } /// gestures those have higher priority than drawer controller's gesture open var higherPriorityGestures: [UIGestureRecognizer] { get { return containerView.higherPriorityGestures } set { containerView.higherPriorityGestures = newValue } } /// gestures those have lower priority than drawer controller's gesture open var lowerPriorityGestures: [UIGestureRecognizer] { get { return containerView.lowerPriorityGestures } set { containerView.lowerPriorityGestures = newValue } } private func setupLeftViewController(_ viewController: UIViewController?) { guard let vc = viewController else { leftWidth = 0 return } addChild(vc) containerView.addSubview(vc.view) vc.view.snp.makeConstraints({ (make) in make.top.left.bottom.equalToSuperview() make.height.equalToSuperview() make.width.equalTo(defaultLeftWidth) }) leftWidth = defaultLeftWidth containerView.setNeedsAdjustTo(.center) if let leftShadow = leftShadowView, let rightShadow = rightShadowView { containerView.bringSubviewToFront(leftShadow) containerView.bringSubviewToFront(rightShadow) } } private func setupRightViewController(_ viewController: UIViewController?) { guard let vc = viewController else { rightWidth = 0 return } addChild(vc) containerView.addSubview(vc.view) vc.view.snp.makeConstraints({ (make) in make.top.bottom.equalToSuperview() make.left.equalTo(centerViewController.view.snp.right) make.height.equalToSuperview() make.width.equalTo(defaultRightWidth) }) rightWidth = defaultRightWidth if let leftShadow = leftShadowView, let rightShadow = rightShadowView { containerView.bringSubviewToFront(leftShadow) containerView.bringSubviewToFront(rightShadow) } vc.didMove(toParent: self) } private func setupMainViewController(_ viewController: UIViewController) { addChild(viewController) containerView.addSubview(viewController.view) viewController.view.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.height.equalToSuperview() make.left.equalTo(leftWidth) make.right.equalTo(-rightWidth) make.width.equalToSuperview() } viewController.didMove(toParent: self) } private func remove(vc: UIViewController?) { vc?.view.snp.removeConstraints() vc?.view.removeFromSuperview() vc?.removeFromParent() vc?.didMove(toParent: nil) } func drawerCoverViewTapped(_ view: ZKDrawerCoverView) { hide(animated: true) } /// 弹出预先设定好的抽屉ViewController /// /// - Parameters: /// - position: 抽屉的位置,center代表隐藏两侧抽屉 /// - animated: 是否有过渡动画 open func show(_ position: Position, animated: Bool) { switch position { case .center: hide(animated: animated) case .left, .right: if let frame = viewController(of: position)?.view.frame { containerView.scrollRectToVisible(frame, animated: animated) } } } /// 传入一个新的ViewController并从右侧弹出 /// /// - Parameters: /// - viewController: ViewController /// - animated: 是否有过渡动画 open func showRight(_ viewController: UIViewController, animated: Bool) { rightViewController = viewController show(.right, animated: animated) } /// 隐藏抽屉 /// /// - Parameter animated: 是否有过渡动画 open func hide(animated: Bool) { if #available(iOS 9.0, *) { self.containerView.setContentOffset(CGPoint.init(x: self.leftWidth, y: 0), animated: animated) } else { UIView.animate(withDuration: 0.3, animations: { self.containerView.contentOffset.x = self.leftWidth }) } } /// 传入一个新的ViewController并从左侧弹出 /// /// - Parameters: /// - viewController: ViewController /// - animated: 是否有过渡动画 open func showLeft(_ viewController: UIViewController, animated: Bool) { leftViewController = viewController show(.left, animated: animated) } } extension ZKDrawerController: UIScrollViewDelegate { open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { scrollView.panGestureRecognizer.isEnabled = false } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollView.panGestureRecognizer.isEnabled = true } open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let offset = scrollView.contentOffset if velocity.x == 0 { if offset.x > leftWidth + rightWidth / 2 { targetContentOffset.pointee.x = rightWidth + leftWidth } else if offset.x < leftWidth / 2 { targetContentOffset.pointee.x = 0 } else { targetContentOffset.pointee.x = leftWidth } } else if velocity.x > 0 { if offset.x > leftWidth { targetContentOffset.pointee.x = rightWidth + leftWidth } else { targetContentOffset.pointee.x = leftWidth } } else { if offset.x < leftWidth { targetContentOffset.pointee.x = 0 } else { targetContentOffset.pointee.x = leftWidth } } } private var progress: CGFloat { let width = containerView.frame.size.width let offsetX = containerView.contentOffset.x if currentPosition == .left { return (leftWidth - offsetX) / leftWidth } else if currentPosition == .right { return (width + rightWidth - containerView.contentSize.width + offsetX) / rightWidth } return 0 } private var scale: CGFloat { if currentPosition == .left || currentPosition == .right { return 1 + progress * (mainScale - 1) } else { return 1 } } private func updateTransforms() { let width = containerView.frame.size.width let progress = self.progress let scale = self.scale let centerView = centerViewController.view! centerView.transform = CGAffineTransform(scaleX: scale, y: scale) mainCoverView.alpha = progress if progress == 0 { centerView.sendSubviewToBack(mainCoverView) } else { centerView.bringSubviewToFront(mainCoverView) } if currentPosition == .left { switch drawerStyle { case .plain: centerView.transform.tx = -(1 - scale) * width / 2 case .cover: centerView.transform.tx = (1 - scale) * width / 2 - leftWidth * progress rightShadowView.alpha = progress case .insert: leftShadowView.alpha = progress centerView.transform.tx = -(1 - scale) * width / 2 } } else if currentPosition == .right { switch drawerStyle { case .plain: centerView.transform.tx = (1 - scale) * width / 2 case .cover: centerView.transform.tx = -(1 - scale) * width / 2 + rightWidth * progress leftShadowView.alpha = progress case .insert: rightShadowView.alpha = progress centerView.transform.tx = (1 - scale) * width / 2 } } else { centerView.transform.tx = 0 leftShadowView.alpha = 0 rightShadowView.alpha = 0 } } open func scrollViewDidScroll(_ scrollView: UIScrollView) { // if on rotating transition, do nothing if isTransitioning { return } // notify willShow to delegate if lastPosition != currentPosition && currentPosition != .center { if let vc = rightViewController, currentPosition == .right { delegate?.drawerController(self, willShow: vc) } else if let vc = leftViewController, currentPosition == .left { delegate?.drawerController(self, willShow: vc) } } lastPosition = currentPosition // hide keyboard containerView.endEditing(true) updateTransforms() } } extension ZKDrawerController { var rightWidth: CGFloat { set { containerView.rightWidth = newValue centerViewController.view.snp.updateConstraints { (update) in update.right.equalTo(-newValue) } } get { return containerView.rightWidth } } var leftWidth: CGFloat { set { containerView.leftWidth = newValue centerViewController.view.snp.updateConstraints { (update) in update.left.equalTo(newValue) } } get { return containerView.leftWidth } } /// 抽屉风格 open var drawerStyle: Style { set { containerView.drawerStyle = newValue switch newValue { case .plain: rightShadowView.isHidden = true leftShadowView.isHidden = true case .insert: rightShadowView.isHidden = false leftShadowView.isHidden = false leftShadowView.snp.remakeConstraints { (make) in make.right.equalTo(centerViewController.view.snp.left) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } rightShadowView.snp.remakeConstraints { (make) in make.left.equalTo(centerViewController.view.snp.right) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } case .cover: rightShadowView.isHidden = false leftShadowView.isHidden = false leftShadowView.snp.remakeConstraints { (make) in make.right.equalTo(centerViewController.view) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } rightShadowView.snp.remakeConstraints { (make) in make.left.equalTo(centerViewController.view) make.top.bottom.equalToSuperview() make.width.equalTo(shadowWidth) } } } get { return containerView.drawerStyle } } /// 主视图上用来拉出抽屉的手势生效区域距边缘的宽度 open var gestureRecognizerWidth: CGFloat { set { containerView.gestureRecognizerWidth = newValue } get { return containerView.gestureRecognizerWidth } } /// 当前状态 open var currentPosition: Position { if containerView.contentOffset.x < leftWidth { return .left } else if containerView.contentOffset.x > leftWidth { return .right } else { return .center } } }
ad37756d998a4df89daedc9955549731
31.465077
153
0.585349
false
false
false
false
rxwei/cuda-swift
refs/heads/master
Sources/Warp/KernelSources.swift
mit
1
// // KernelSources.swift // CUDA // // Created by Richard Wei on 11/3/16. // // extension StaticString : Equatable { public static func == (lhs: StaticString, rhs: StaticString) -> Bool { return lhs.utf8Start == rhs.utf8Start } } protocol SourceHashable : Equatable, Hashable { var source: String { get } } extension SourceHashable where Self : RawRepresentable, Self.RawValue == StaticString { var source: String { return String(bytesNoCopy: UnsafeMutablePointer(mutating: rawValue.utf8Start), length: rawValue.utf8CodeUnitCount, encoding: .utf8, freeWhenDone: false)! } } /// Kernel source with generic TYPE /// /// - sum: void sum(T*, SIZE, T*) /// - asum: void asum(T*, SIZE, T*) /// - fill: void fill(T*, SIZE) enum KernelSource: StaticString, SourceHashable { case sum = "KN(TYPE *v, SIZE c, TYPE *res){*res=0; for (long i=0; i<c; i++) *res+=v[i];}" // TODO: parallelism case asum = "KN(TYPE *v, SIZE c, TYPE *res){*res=0; for (long i=0; i<c; i++) *res+=abs(v[i]);}" // TODO: parallelism case fill = "KN(TYPE *v, TYPE x, SIZE c){ID(i); if (i<c) v[i]=x;}" } /// Kernel source with generic T and 1-place transformation function FUNC (eg. tan, sin) /// /// - transform: void transform(T*, SIZE, T*) enum FunctorialKernelSource: StaticString, SourceHashable { case transform = "KN(TYPE *v, SIZE c, TYPE *res){ID(i); if (i<c) res[i]=FUNC(v[i]);}" } /// Kernel source with generic TYPE and binary operation OP /// /// - elementwise: void elementwise(T, T*, T, T*, SIZE, T*) /// - scalarRight: void scalarRight(T, T*, T, SIZE, T*) /// - scalarLeft: void scalarRight(T, T, T*, SIZE, T*) enum BinaryOperationKernelSource: StaticString, SourceHashable { case elementwise = "KN(TYPE a, TYPE *x, TYPE b, TYPE *y, SIZE c, TYPE *res) {ID(i); if (i<c) res[i] = OP(a*x[i],b*y[i]);}" case scalarRight = "KN(TYPE a, TYPE *x, TYPE rval, SIZE c, TYPE *res) {ID(i); if (i<c) res[i] = OP(a*x[i],rval);}" case scalarLeft = "KN(TYPE lval, TYPE a, TYPE *x, SIZE c, TYPE *res) {ID(i); if (i<c) res[i] = OP(lval,a*x[i]);}" } extension StaticString : Hashable { public var hashValue: Int { return utf8Start.hashValue } }
86ad92bbcb8cd2601d7eb01a1dd353a4
35.403226
126
0.615862
false
false
false
false
cottonBuddha/Qsic
refs/heads/master
Qsic/QSMusicController.swift
mit
1
// // QSMusicController.swift // Qsic // // Created by cottonBuddha on 2017/7/12. // Copyright © 2017年 cottonBuddha. All rights reserved. // import Foundation import Darwin enum MenuType: Int { case Home case Artist case Song case Album case SongOrAlbum case SongOrList case Ranking case Search case Help case PlayList case SongListFirstClass case SongListSecondClass case SongLists } public protocol KeyEventProtocol { func handleWithKeyEvent(keyCode:Int32) } class QSMusicController : PlayerControlable { private var navtitle : QSNaviTitleWidget? private var menu : QSMenuWidget? private var menuStack : [QSMenuModel] = [] private var getChThread : Thread? private var searchBar : QSSearchWidget? private var loginWidget : QSLoginWidget? private var player : QSPlayer = QSPlayer.shared private var isHintOn: Bool = false private var dancer: QSProgressWidget = QSProgressWidget.init(startX: 0, startY: 0, type: .Dancer) var mainwin : QSMainWindow = QSMainWindow.init() func start() { self.menu = self.initHomeMenu() self.mainwin.addSubWidget(widget: self.menu!) self.navtitle = self.initNaviTitle() self.mainwin.addSubWidget(widget: self.navtitle!) self.navtitle?.push(title: self.menu!.title) self.player.delegate = self self.getChThread = Thread.init(target: self, selector: #selector(QSMusicController.listenToInstructions), object: nil) self.getChThread?.start() self.mainwin.addSubWidget(widget: dancer) NotificationCenter.default.addObserver(self, selector: #selector(QSMusicController.songChanged), name:Notification.Name(rawValue: kNotificationSongHasChanged), object: nil) RunLoop.main.run() } private func initNaviTitle() -> QSNaviTitleWidget { let naviTitle = QSNaviTitleWidget.init(startX: 3, startY: 1, width: Int(COLS - 3 - 1), height: 1) return naviTitle } private func initHomeMenu() -> QSMenuWidget { let menuData = [("榜单",0), ("推荐",1), ("歌手",2), ("歌单",3), ("收藏",4), ("搜索",5), ("帮助",6)] var menuItems : [MenuItemModel] = [] menuData.forEach { let item = MenuItemModel.init(title: $0.0, code: $0.1) menuItems.append(item) } let nickName = UserDefaults.standard.value(forKey: UD_USER_NICKNAME) as? String ?? "网易云音乐" let dataModel = QSMenuModel.init(title: nickName, type:MenuType.Home, items: menuItems, currentItemCode: 0) self.menuStack.append(dataModel) let mainMenu = QSMenuWidget.init(startX: 3, startY: 3, width: Int(COLS-6), dataModel: dataModel) { (type,item) in if let menuType = MenuType.init(rawValue: type) { switch menuType { case MenuType.Home: self.handleHomeSelection(item: item) case MenuType.Artist: self.handleArtistSelection(item: item as! ArtistModel) case MenuType.SongOrAlbum: self.handleSongOrAlbumSelection(item: item as! SongOrAlbumModel) case MenuType.Song, MenuType.PlayList: self.handleSongSelection(item: item as! SongModel) case MenuType.Ranking: self.handleRankingSelection(item: item as! RankingModel) case MenuType.Album: self.handleAlbumSelection(item: item as! AlbumModel) case MenuType.Search: self.handleSearchTypeSelection(item: item as! SearchModel) case MenuType.SongListFirstClass: self.handleSongListFirstClassSelection(item: item) case MenuType.SongListSecondClass: self.handleSongListSecondClassSelection(item: item) case MenuType.SongLists: self.handleSongListsSelection(item: item as! SongListModel) case MenuType.SongOrList: self.handleSongOrListSelection(item: item) default: break } } } return mainMenu } private func handleHomeSelection(item:MenuItemModel) { let code = item.code switch code { case 0: API.shared.rankings(completionHandler: { [unowned self] (rankings) in let dataModel = QSMenuModel.init(title: "榜单", type: MenuType.Ranking, items: rankings, currentItemCode: 0) self.push(menuModel: dataModel) }) case 1: let menuData = [("推荐歌曲",0),("推荐歌单",1)] var menuItems : [MenuItemModel] = [] menuData.forEach { let item = MenuItemModel.init(title: $0.0, code: $0.1) menuItems.append(item) } let dataModel = QSMenuModel.init(title: "推荐", type:MenuType.SongOrList, items: menuItems, currentItemCode: 0) self.push(menuModel: dataModel) case 2: self.menu?.showProgress() API.shared.artists { [unowned self] (artists) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: "歌手", type:MenuType.Artist, items: artists, currentItemCode: 0) self.push(menuModel: dataModel) } case 3: let models = generateListClassModels() let dataModel = QSMenuModel.init(title: "歌单", type: MenuType.SongListFirstClass, items: models, currentItemCode: 0) self.push(menuModel: dataModel) case 4: self.menu?.showProgress() API.shared.userList(completionHandler: { [unowned self] (models) in self.menu?.hideProgress() if models.count > 0 { let dataModel = QSMenuModel.init(title: "收藏", type:MenuType.SongLists, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } else { self.showHint(with: "提示:接口出错,或未登录,请按\"d\"键进行登录", at: 11) } }) case 5: self.handleSearchCommandKey() case 6: let models = generateHelpModels() let menuModel = QSMenuModel.init(title: "帮助", type: MenuType.Help, items: models, currentItemCode: 0) self.push(menuModel: menuModel) default: break } } private func handleArtistSelection(item:ArtistModel) { let itemModels = generateSongOrAlbumModels(artistId: item.id) let dataModel = QSMenuModel.init(title: item.name, type: MenuType.SongOrAlbum, items: itemModels, currentItemCode: 0) self.push(menuModel: dataModel) } private func handleSongOrAlbumSelection(item:SongOrAlbumModel) { let code = item.code switch code { case 0: self.menu?.showProgress() API.shared.getSongsOfArtist(artistId: item.artistId) { [unowned self] (models) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: "歌曲", type:MenuType.Song, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } case 1: self.menu?.showProgress() API.shared.getAlbumsOfArtist(artistId: item.artistId, completionHandler: { [unowned self] (models) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: "专辑", type: MenuType.Album, items: models, currentItemCode: 0) self.push(menuModel: dataModel) }) default: break } } private func handleSongSelection(item:SongModel) { player.songList = self.menuStack.last?.items as! [SongModel] player.currentIndex = item.code if player.currentSongId != nil && player.currentSongId! == player.songList[player.currentIndex].id { return } player.play() } private func handleRankingSelection(item:RankingModel) { self.menu?.showProgress() API.shared.songListDetail(listId: item.id) { [unowned self] (models) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: item.title, type: MenuType.Song, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } } private func handleAlbumSelection(item:AlbumModel) { API.shared.getSongsOfAlbum(albumId: item.id) { [unowned self] (models) in let dataModel = QSMenuModel.init(title: item.name, type: MenuType.Song, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } } private func handleSearchTypeSelection(item:SearchModel) { var searchType = SearchType.Song switch item.code { case 0: searchType = SearchType.Song case 1: searchType = SearchType.Artist case 2: searchType = SearchType.Album case 3: searchType = SearchType.List default: break } self.menu?.showProgress() API.shared.search(type: searchType, content: item.content) { [unowned self] (type, models) in self.menu?.hideProgress() switch type { case .Song: let menuModel = QSMenuModel.init(title: "歌曲", type:MenuType.Song, items: models, currentItemCode: 0) self.push(menuModel: menuModel) case .Artist: let menuModel = QSMenuModel.init(title: "歌手", type: MenuType.Artist, items: models, currentItemCode: 0) self.push(menuModel: menuModel) case .Album: let menuModel = QSMenuModel.init(title: "专辑", type: MenuType.Album, items: models, currentItemCode: 0) self.push(menuModel: menuModel) case .List: let menuModel = QSMenuModel.init(title: "歌单", type: MenuType.SongLists, items: models, currentItemCode: 0) self.push(menuModel: menuModel) //mvaddstr(2, 2, models.first?.title) } } } private func handleSongListFirstClassSelection(item:MenuItemModel) { let code = item.code var models: [MenuItemModel] = [] switch code { case 0: models = generateSongListModels(type: .Languages) case 1: models = generateSongListModels(type: .Style) case 2: models = generateSongListModels(type: .Scenario) case 3: models = generateSongListModels(type: .Emotion) case 4: models = generateSongListModels(type: .Theme) default : break } let dataModel = QSMenuModel.init(title: item.title, type: MenuType.SongListSecondClass, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } private func handleSongListSecondClassSelection(item:MenuItemModel) { self.menu?.showProgress() API.shared.songlists(type: item.title) { [unowned self] (models) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: item.title, type: MenuType.SongLists, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } } private func handleSongListsSelection(item:SongListModel) { self.menu?.showProgress() API.shared.songListDetail(listId: item.id, completionHandler: { [unowned self] (songModels) in self.menu?.hideProgress() let dataModel = QSMenuModel.init(title: item.title, type: MenuType.Song, items: songModels, currentItemCode: 0) self.push(menuModel: dataModel) }) } private func handleAddToMyListSelection(item:SongListModel) { API.shared.addSongToMyList(tracks: item.idOfTheSongShouldBeAdded, pid: item.id) { [unowned self] (finish) in if finish { self.showHint(with: "添加完成,请返回↵", at: 14) } else { self.showHint(with: "添加失败,请返回↵", at: 14) } } } private func handleSongOrListSelection(item:MenuItemModel) { let code = item.code switch code { case 0: self.menu?.showProgress() API.shared.recommendSongs(completionHandler: { [unowned self] (models) in self.menu?.hideProgress() if models.count > 0 { let dataModel = QSMenuModel.init(title: "歌曲", type:MenuType.Song, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } else { self.showHint(with: "提示:接口出错,或未登录,请返回首页按\"d\"键进行登录", at: 11) } }) case 1: self.menu?.showProgress() API.shared.recommendPlayList(completionHandler: { [unowned self] (models) in self.menu?.hideProgress() if models.count > 0 { let dataModel = QSMenuModel.init(title: "专辑", type:MenuType.SongLists, items: models, currentItemCode: 0) self.push(menuModel: dataModel) } else { self.showHint(with: "提示:接口出错,或未登录,请返回首页按\"d\"键进行登录", at: 11) } }) default: break } } private func handleLoginCommandKey() { guard menuStack.last?.type == MenuType.Home.rawValue else { beep() return } if player.isPlaying { dancer.pause() } let startY = menuStack.last?.type == MenuType.Home.rawValue ? 11 : 14 self.loginWidget = QSLoginWidget.init(startX: 3, startY: startY) self.mainwin.addSubWidget(widget: self.loginWidget!) self.loginWidget?.getInputContent(completionHandler: { (account, password) in API.shared.login(account: account, password: password, completionHandler: { [unowned self] (accountNameAndId) in if self.player.isPlaying { self.dancer.load() } self.removeLoginWidget() if accountNameAndId.0 != "" { self.navtitle?.titleStack.removeFirst() self.navtitle?.titleStack.insert(accountNameAndId.0, at: 0) self.navtitle?.drawWidget() UserDefaults.standard.set(accountNameAndId.0, forKey: UD_USER_NICKNAME) UserDefaults.standard.set(accountNameAndId.1, forKey: UD_USER_ID) self.showHint(with: "登录成功!", at: 11) } else { self.showHint(with: "登录失败!", at: 11) } }) }) } private func handleSearchCommandKey() { guard menuStack.last?.type == MenuType.Home.rawValue else { beep() return } if player.isPlaying { dancer.pause() } let startY = 11 searchBar = QSSearchWidget.init(startX: 3, startY: startY) mainwin.addSubWidget(widget: searchBar!) searchBar?.getInputContent(completionHandler: {[unowned self] (content) in if self.player.isPlaying { self.dancer.load() } self.searchBar?.eraseSelf() self.mainwin.removeSubWidget(widget: self.searchBar!) if content == "" { return } let models = generateSearchTypeModels(content: content) let menuModel = QSMenuModel.init(title: "搜索", type: MenuType.Search, items: models, currentItemCode: 0) self.push(menuModel: menuModel) }) } private func handlePlayListCommandKey() { if player.songList.count > 0 && menuStack.last?.type != MenuType.PlayList.rawValue{ let menuModel = QSMenuModel.init(title: "播放列表", type: MenuType.PlayList, items: player.songList, currentItemCode: player.currentIndex) self.push(menuModel: menuModel) } else { beep() } } private func handleAddToMyListCommandKey() { let lastMenu = menuStack.last guard lastMenu?.type == MenuType.Song.rawValue else { beep() return } let currentItem = lastMenu?.items[lastMenu!.currentItemCode] as! SongModel API.shared.like(id: currentItem.id) { [unowned self] (finish) in let hint = finish ? "已添加至喜欢↵" : "添加失败↵" self.showHint(with: hint, at: 14) } } @objc func listenToInstructions() { var ic : Int32 = 0 repeat { ic = getch() if isHintOn && ic != CMD_PLAYMODE_SINGLE && ic != CMD_PLAYMODE_ORDER && ic != CMD_PLAYMODE_SHUFFLE{ self.hideHint() continue } //mvwaddstr(self.mainwin.window, 2, 2, "\(ic)") self.handleWithKeyEvent(keyCode: ic) self.player.handleWithKeyEvent(keyCode: ic) self.menu?.handleWithKeyEvent(keyCode: ic) } while (ic != CMD_QUIT && ic != CMD_QUIT_LOGOUT) curs_set(1) if ic == CMD_QUIT_LOGOUT { API.shared.clearLoginCookie { UserDefaults.standard.removeObject(forKey: UD_USER_NICKNAME) UserDefaults.standard.removeObject(forKey: UD_USER_ID) } } DispatchQueue.main.async { self.menu?.eraseSelf() self.navtitle?.eraseSelf() self.dancer.eraseSelf() self.mainwin.end() NotificationCenter.default.removeObserver(self) exit(0) } } private func push(menuModel:QSMenuModel) { self.menuStack.append(menuModel) self.menu?.presentMenuWithModel(menuModel: menuModel) self.navtitle?.push(title: menuModel.title) } private func pop() { if self.menuStack.count > 1 { self.menuStack.removeLast() self.menu?.presentMenuWithModel(menuModel: self.menuStack.last!) self.navtitle?.pop() } } private func handleWithKeyEvent(keyCode:Int32) { if menu?.progress != nil, menu!.progress!.isLoading { return } switch keyCode { case CMD_BACK.0, CMD_BACK.1: self.pop() case CMD_SEARCH: self.handleSearchCommandKey() case CMD_LOGIN: self.handleLoginCommandKey() case CMD_PLAY_LIST: self.handlePlayListCommandKey() case CMD_GITHUB: let task = Process.init() task.launchPath = "/bin/bash" task.arguments = ["-c","open https://github.com/cottonBuddha/Qsic"] task.launch() case CMD_PLAYMODE_SINGLE: let startY = menuStack.last?.type == MenuType.Home.rawValue ? 11 : 14 showHint(with: "设置为:单曲循环↵", at: startY) beep() case CMD_PLAYMODE_ORDER: let startY = menuStack.last?.type == MenuType.Home.rawValue ? 11 : 14 showHint(with: "设置为:顺序播放↵", at: startY) beep() case CMD_PLAYMODE_SHUFFLE: let startY = menuStack.last?.type == MenuType.Home.rawValue ? 11 : 14 showHint(with: "设置为:随机播放↵", at: startY) beep() case CMD_ADD_LIKE: self.handleAddToMyListCommandKey() default: break } } private var contentLength = 0 private var lineNum = 0 private func showHint(with content: String, at lineNum: Int) { isHintOn = true contentLength = content.lengthInCurses() self.lineNum = lineNum mvwaddstr(self.mainwin.window, Int32(lineNum), 3, content) refresh() } private func hideHint() { isHintOn = false mvwaddstr(self.mainwin.window, Int32(lineNum), 3, contentLength.space) contentLength = 0 move(0, 0) refresh() } private func removeLoginWidget() { guard loginWidget != nil else { return } loginWidget?.hide() loginWidget = nil } @objc func songChanged() { navtitle?.currentSong = player.songList[player.currentIndex].title navtitle?.drawWidget() } func playerWillPlay() { self.dancer.load() } func playerWillPause() { self.dancer.pause() } }
91678e93241aff7f9df24cc0227bf99c
37.569316
180
0.573277
false
false
false
false
leftdal/youslow
refs/heads/master
iOS/YouTubeView/YTPlayerView.swift
gpl-3.0
1
// // YTPlayerView.swift // Demo // // Created by to0 on 2/1/15. // Copyright (c) 2015 to0. All rights reserved. // import UIKit protocol YTPlayerDelegate { // func playerHadIframeApiReady(playerView: YTPlayerView) func playerDidBecomeReady(playerView: YTPlayerView) func playerDidChangeToState(playerView: YTPlayerView, state: YTPlayerState) func playerDidChangeToQuality(playerView: YTPlayerView, quality: YTPlayerQuality) } class YTPlayerView: UIView, UIWebViewDelegate { let originalUrl = "about:blank" var videoId = "" var delegate: YTPlayerDelegate? var webView: UIWebView? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // loadPlayerWithOptions(nil) } override init(frame: CGRect) { super.init(frame: frame) // loadPlayerWithOptions(nil) } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ func loadVideoById(id: String) { let js = "player.loadVideoById('\(id)', 0, 'medium');" self.evaluateJavaScript(js) } func loadPlayerWithOptions(id: String) -> Bool { let bundle = NSBundle.mainBundle(); let path = NSBundle.mainBundle().pathForResource("YTPlayerIframeTemplate", ofType: "html") if path == nil { return false } var err: NSError? // let template = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) as! String // let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: NSStringCompareOptions.allZeros, range: nil) let template = try! String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil) if err != nil { return false } newWebView() webView?.loadHTMLString(iframe, baseURL: NSURL(string: originalUrl)) webView?.delegate = self // self.webView?.allowsInlineMediaPlayback = true // self.webView?.mediaPlaybackRequiresUserAction = false return true } func playVideo() { evaluateJavaScript("player.playVideo();") } func destroyPlayer() { evaluateJavaScript("player.destroy();") } func getVideoDuration() -> String? { return evaluateJavaScript("player.getDuration().toString();") } func getVideoLoadedFraction() -> String? { return evaluateJavaScript("player.getVideoLoadedFraction().toString();") } func getAvailableQualityLevelsString() -> String? { return evaluateJavaScript("player.getAvailableQualityLevels().toString();") } private func evaluateJavaScript(js: String) -> String? { return self.webView?.stringByEvaluatingJavaScriptFromString(js) } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { print(error) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url: NSURL if request.URL == nil { return false } url = request.URL! if url.host == originalUrl { return true } else if url.scheme == "http" || url.scheme == "https" { return shouldNavigateToUrl(url) } if url.scheme == "ytplayer" { delegateEvents(url) return false } return true } func webViewDidStartLoad(webView: UIWebView) { print(webView.request?.URL) } private func shouldNavigateToUrl(url: NSURL) -> Bool { return true } /** * Private method to handle "navigation" to a callback URL of the format * ytplayer://action?data=someData */ private func delegateEvents(event: NSURL) { let action: String = event.host! let callback: YTPlayerCallback? = YTPlayerCallback(rawValue: action) let query = event.query let data = query?.substringFromIndex(query!.startIndex.advancedBy(5)) if callback == nil { return } switch callback! { case .OnYouTubeIframeAPIReady: print("api ready") // delegate?.playerHadIframeApiReady(self) case .OnReady: delegate?.playerDidBecomeReady(self) case .OnStateChange: if let state = YTPlayerState(rawValue: data!) { delegate?.playerDidChangeToState(self, state: state) } case .OnPlaybackQualityChange: if let quality = YTPlayerQuality(rawValue: data!) { delegate?.playerDidChangeToQuality(self, quality: quality) } default: print("error: \(data)") } } // add and remove webview private func newWebView() { removeWebView() let newWebView = UIWebView(frame: self.bounds) newWebView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] newWebView.scrollView.scrollEnabled = false newWebView.scrollView.bounces = false newWebView.allowsInlineMediaPlayback = true newWebView.mediaPlaybackRequiresUserAction = false newWebView.translatesAutoresizingMaskIntoConstraints = false webView = newWebView addSubview(self.webView!) } func removeWebView() { destroyPlayer() webView?.loadHTMLString("", baseURL: NSURL(string: originalUrl)) webView?.stopLoading() webView?.delegate = nil webView?.removeFromSuperview() webView = nil } }
95647ad0d607dc00a8d308d92b098bf8
32.933333
154
0.614113
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Frontend/Browser/HistorySwiper.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ class HistorySwiper : NSObject { var topLevelView: UIView! var webViewContainer: UIView! func setup(_ topLevelView: UIView, webViewContainer: UIView) { self.topLevelView = topLevelView self.webViewContainer = webViewContainer goBackSwipe.delegate = self goForwardSwipe.delegate = self } lazy var goBackSwipe: UIGestureRecognizer = { let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenLeftEdgeSwiped(_:))) self.topLevelView.addGestureRecognizer(pan) return pan }() lazy var goForwardSwipe: UIGestureRecognizer = { let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenRightEdgeSwiped(_:))) self.topLevelView.addGestureRecognizer(pan) return pan }() @objc func updateDetected() { restoreWebview() } func screenWidth() -> CGFloat { return topLevelView.frame.width } fileprivate func handleSwipe(_ recognizer: UIGestureRecognizer) { if getApp().browserViewController.homePanelController != nil { return } guard let tab = getApp().browserViewController.tabManager.selectedTab, let webview = tab.webView else { return } let p = recognizer.location(in: recognizer.view) let shouldReturnToZero = recognizer == goBackSwipe ? p.x < screenWidth() / 2.0 : p.x > screenWidth() / 2.0 if recognizer.state == .ended || recognizer.state == .cancelled || recognizer.state == .failed { UIView.animate(withDuration: 0.25, animations: { if shouldReturnToZero { self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty) } else { let x = recognizer == self.goBackSwipe ? self.screenWidth() : -self.screenWidth() self.webViewContainer.transform = CGAffineTransform(translationX: x, y: self.webViewContainer.transform.ty) self.webViewContainer.alpha = 0 } }, completion: { (Bool) -> Void in if !shouldReturnToZero { if recognizer == self.goBackSwipe { getApp().browserViewController.goBack() } else { getApp().browserViewController.goForward() } self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty) // when content size is updated postAsyncToMain(3.0) { self.restoreWebview() } NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationPageInteractive), object: webview) NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationWebViewLoadCompleteOrFailed), object: webview) } }) } else { let tx = recognizer == goBackSwipe ? p.x : p.x - screenWidth() webViewContainer.transform = CGAffineTransform(translationX: tx, y: self.webViewContainer.transform.ty) } } func restoreWebview() { NotificationCenter.default.removeObserver(self) postAsyncToMain(0.4) { // after a render detected, allow ample time for drawing to complete UIView.animate(withDuration: 0.2, animations: { self.webViewContainer.alpha = 1.0 }) } } @objc func screenRightEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) { handleSwipe(recognizer) } @objc func screenLeftEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) { handleSwipe(recognizer) } } extension HistorySwiper : UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool { guard let tab = getApp().browserViewController.tabManager.selectedTab else { return false} if (recognizer == goBackSwipe && !tab.canGoBack) || (recognizer == goForwardSwipe && !tab.canGoForward) { return false } guard let recognizer = recognizer as? UIPanGestureRecognizer else { return false } let v = recognizer.velocity(in: recognizer.view) if fabs(v.x) < fabs(v.y) { return false } let tolerance = CGFloat(30.0) let p = recognizer.location(in: recognizer.view) return recognizer == goBackSwipe ? p.x < tolerance : p.x > screenWidth() - tolerance } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
518ab3f04c5c9873a55e8ae10e8c1191
44.916667
237
0.615426
false
false
false
false
ApplauseOSS/Swifjection
refs/heads/master
Sources/Swifjection/Classes/SwifjectorSpec.swift
mit
1
import Quick import Nimble @testable import Swifjection class InjectingSpec: QuickSpec { override func spec() { var injector: Swifjector! var bindings: Bindings! beforeEach { bindings = Bindings() injector = Swifjector(bindings: bindings) } describe("getObject(withType:)") { context("without any bindings") { it("should not return object conforming to protocol") { expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beNil()) } it("should not return empty swift object") { expect(injector.getObject(withType: EmptySwiftClass.self)).to(beNil()) } it("should return injectable object") { expect(injector.getObject(withType: InjectableClass.self)).notTo(beNil()) } it("should inject dependencies in injectable object") { expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should return injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should return ObjC object") { expect(injector.getObject(withType: ObjCClass.self)).to(beAKindOf(ObjCClass.self)) } } context("with bindings with implicitly unwrapped objects") { var objectConformingToProtocol: ClassConformingToProtocol! var structConformingToProtocol: StructConformingToProtocol! var emptySwiftObject: EmptySwiftClass! var injectableObject: InjectableClass! var injectableObjCObject: InjectableObjCClass! var objCObject: ObjCClass! beforeEach { objectConformingToProtocol = ClassConformingToProtocol() structConformingToProtocol = StructConformingToProtocol() emptySwiftObject = EmptySwiftClass() injectableObject = InjectableClass(injector: injector) injectableObjCObject = InjectableObjCClass(injector: injector) objCObject = ObjCClass() } context("for object conforming to protocol") { beforeEach { bindings.bind(object: objectConformingToProtocol, toType: EmptySwiftProtocol.self) } it("should have object conforming to protocol injected") { let object = injector.getObject(withType: EmptySwiftProtocol.self) expect(object).to(beIdenticalTo(objectConformingToProtocol)) } } context("for struct conforming to protocol") { beforeEach { bindings.bind(object: structConformingToProtocol, toType: EmptySwiftProtocol.self) } it("should have struct conforming to protocol injected") { let object = injector.getObject(withType: EmptySwiftProtocol.self) expect(object).to(beAnInstanceOf(StructConformingToProtocol.self)) } } context("for other cases") { beforeEach { bindings.bind(object: emptySwiftObject, toType: EmptySwiftClass.self) bindings.bind(object: injectableObject, toType: InjectableClass.self) bindings.bind(object: injectableObjCObject, toType: InjectableObjCClass.self) bindings.bind(object: objCObject, toType: ObjCClass.self) } it("should have empty swift object injected") { expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beFalse()) } it("should have injectable ObjC object injected") { expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beFalse()) } it("should have ObjC object injected") { expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject)) } } } context("with bindings") { var objectConformingToProtocol: ClassConformingToProtocol? var emptySwiftObject: EmptySwiftClass? var injectableObject: InjectableClass? var injectableObjCObject: InjectableObjCClass? var objCObject: ObjCClass? beforeEach { objectConformingToProtocol = ClassConformingToProtocol() emptySwiftObject = EmptySwiftClass() injectableObject = InjectableClass(injector: injector) injectableObjCObject = InjectableObjCClass(injector: injector) objCObject = ObjCClass() } context("object bindings") { beforeEach { bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self) bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self) bindings.bind(object: injectableObject!, toType: InjectableClass.self) bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self) bindings.bind(object: objCObject!, toType: ObjCClass.self) } it("should have object conforming to protocol injected") { expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beIdenticalTo(objectConformingToProtocol)) } it("should have empty swift object injected") { expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beFalse()) } it("should have injectable ObjC object injected") { expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beFalse()) } it("should have ObjC object injected") { expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject)) } } context("closure bindings") { beforeEach { injectableObject?.injectDependencies(injector: injector) injectableObjCObject?.injectDependencies(injector: injector) bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return objectConformingToProtocol! } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return emptySwiftObject! } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in return injectableObject! } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in return injectableObjCObject! } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return objCObject! } } it("should not have object conforming to protocol injected") { expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beIdenticalTo(objectConformingToProtocol)) } it("should not have empty swift object injected") { expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject)) } } context("closure bindings with new instances") { beforeEach { bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return ClassConformingToProtocol() } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return EmptySwiftClass() } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in let injectableObject = InjectableClass() injectableObject.injectDependencies(injector: injector) return injectableObject } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in let injectableObjCObject = InjectableObjCClass() injectableObjCObject.injectDependencies(injector: injector) return injectableObjCObject } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return ObjCClass() } } it("should not have object conforming to protocol injected") { expect(injector.getObject(withType: EmptySwiftProtocol.self)).notTo(beNil()) } it("should not have empty swift object injected") { expect(injector.getObject(withType: EmptySwiftClass.self)).notTo(beNil()) } it("should have injectable object injected") { expect(injector.getObject(withType: InjectableClass.self)).notTo(beNil()) } it("should inject dependencies in injectable object") { expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(injector.getObject(withType: InjectableObjCClass.self)).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(injector.getObject(withType: ObjCClass.self)).to(beAKindOf(ObjCClass.self)) } } } } describe("subscript") { context("without any bindings") { it("should not return object conforming to protocol") { expect(injector[EmptySwiftProtocol.self]).to(beNil()) } it("should not return empty swift object") { expect(injector[EmptySwiftClass.self]).to(beNil()) } it("should return injectable object") { expect(injector[InjectableClass.self]).notTo(beNil()) } it("should inject dependencies in injectable object") { expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue()) } it("should return injectable ObjC object") { let object = injector[InjectableObjCClass.self as Injectable.Type] expect(object).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue()) } it("should return ObjC object") { expect(injector[ObjCClass.self]).to(beAKindOf(ObjCClass.self)) } } context("with bindings") { var objectConformingToProtocol: ClassConformingToProtocol? var emptySwiftObject: EmptySwiftClass? var injectableObject: InjectableClass? var injectableObjCObject: InjectableObjCClass? var objCObject: ObjCClass? beforeEach { objectConformingToProtocol = ClassConformingToProtocol() emptySwiftObject = EmptySwiftClass() injectableObject = InjectableClass(injector: injector) injectableObjCObject = InjectableObjCClass(injector: injector) objCObject = ObjCClass() } context("object bindings") { beforeEach { bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self) bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self) bindings.bind(object: injectableObject!, toType: InjectableClass.self) bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self) bindings.bind(object: objCObject!, toType: ObjCClass.self) } it("should not have object conforming to protocol injected") { expect(injector[EmptySwiftProtocol.self]).to(beIdenticalTo(objectConformingToProtocol)) } it("should not have empty swift object injected") { expect(injector[EmptySwiftClass.self]).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(injector[InjectableClass.self]).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beFalse()) } it("should have injectable ObjC object injected") { expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beFalse()) } it("should have ObjC object injected") { expect(injector[ObjCClass.self]).to(beIdenticalTo(objCObject)) } } context("closure bindings") { beforeEach { injectableObject?.injectDependencies(injector: injector) injectableObjCObject?.injectDependencies(injector: injector) bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return objectConformingToProtocol! } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return emptySwiftObject! } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in return injectableObject! } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in return injectableObjCObject! } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return objCObject! } } it("should not have object conforming to protocol injected") { expect(injector[EmptySwiftProtocol.self]).to(beIdenticalTo(objectConformingToProtocol)) } it("should not have empty swift object injected") { expect(injector[EmptySwiftClass.self]).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(injector[InjectableClass.self]).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(injector[ObjCClass.self]).to(beIdenticalTo(objCObject)) } } context("closure bindings with new instances") { beforeEach { bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return ClassConformingToProtocol() } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return EmptySwiftClass() } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in let injectableObject = InjectableClass() injectableObject.injectDependencies(injector: injector) return injectableObject } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in let injectableObjCObject = InjectableObjCClass() injectableObjCObject.injectDependencies(injector: injector) return injectableObjCObject } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return ObjCClass() } } it("should not have object conforming to protocol injected") { expect(injector[EmptySwiftProtocol.self]).notTo(beNil()) } it("should not have empty swift object injected") { expect(injector[EmptySwiftClass.self]).notTo(beNil()) } it("should have injectable object injected") { expect(injector[InjectableClass.self]).notTo(beNil()) } it("should inject dependencies in injectable object") { expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(injector[ObjCClass.self]).to(beAKindOf(ObjCClass.self)) } } } } describe("injecting dependencies in objects using injectDependencies(injector:) with the injector") { var objectWithDependencies: ClassWithDependencies! context("without any bindings") { beforeEach { objectWithDependencies = ClassWithDependencies(injector: injector) objectWithDependencies?.injectDependencies(injector: injector) } it("should not have object conforming to protocol injected") { expect(objectWithDependencies.objectConformingToProtocol).to(beNil()) } it("should not have empty swift object injected") { expect(objectWithDependencies.emptySwiftObject).to(beNil()) } it("should have injectable object injected") { expect(objectWithDependencies.injectableObject).notTo(beNil()) } it("should inject dependencies in injectable object") { expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(objectWithDependencies.injectableObjCObject).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(objectWithDependencies.objCObject).to(beAKindOf(ObjCClass.self)) } } context("with bindings") { var objectConformingToProtocol: ClassConformingToProtocol? var emptySwiftObject: EmptySwiftClass? var injectableObject: InjectableClass? var injectableObjCObject: InjectableObjCClass? var objCObject: ObjCClass? beforeEach { objectConformingToProtocol = ClassConformingToProtocol() emptySwiftObject = EmptySwiftClass() injectableObject = InjectableClass(injector: injector) injectableObjCObject = InjectableObjCClass(injector: injector) objCObject = ObjCClass() } context("object bindings") { beforeEach { bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self) bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self) bindings.bind(object: injectableObject!, toType: InjectableClass.self) bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self) bindings.bind(object: objCObject!, toType: ObjCClass.self) objectWithDependencies = ClassWithDependencies(injector: injector) objectWithDependencies?.injectDependencies(injector: injector) } it("should not have object conforming to protocol injected") { expect(objectWithDependencies.objectConformingToProtocol).to(beIdenticalTo(objectConformingToProtocol)) } it("should not have empty swift object injected") { expect(objectWithDependencies.emptySwiftObject).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(objectWithDependencies.injectableObject).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beFalse()) } it("should have injectable ObjC object injected") { expect(objectWithDependencies.injectableObjCObject).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beFalse()) } it("should have ObjC object injected") { expect(objectWithDependencies.objCObject).to(beIdenticalTo(objCObject)) } } context("closure bindings") { beforeEach { injectableObject?.injectDependencies(injector: injector) injectableObjCObject?.injectDependencies(injector: injector) bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return objectConformingToProtocol! } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return emptySwiftObject! } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in return injectableObject! } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in return injectableObjCObject! } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return objCObject! } objectWithDependencies = ClassWithDependencies(injector: injector) objectWithDependencies?.injectDependencies(injector: injector) } it("should not have object conforming to protocol injected") { expect(objectWithDependencies.objectConformingToProtocol).to(beIdenticalTo(objectConformingToProtocol)) } it("should not have empty swift object injected") { expect(objectWithDependencies.emptySwiftObject).to(beIdenticalTo(emptySwiftObject)) } it("should have injectable object injected") { expect(objectWithDependencies.injectableObject).to(beIdenticalTo(injectableObject)) } it("should inject dependencies in injectable object") { expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(objectWithDependencies.injectableObjCObject).to(beIdenticalTo(injectableObjCObject)) } it("should inject dependencies in injectable ObjC object") { expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(objectWithDependencies.objCObject).to(beIdenticalTo(objCObject)) } } context("closure bindings with new instances") { beforeEach { bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in return ClassConformingToProtocol() } bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in return EmptySwiftClass() } bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in let injectableObject = InjectableClass() injectableObject.injectDependencies(injector: injector) return injectableObject } bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in let injectableObjCObject = InjectableObjCClass() injectableObjCObject.injectDependencies(injector: injector) return injectableObjCObject } bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in return ObjCClass() } objectWithDependencies = ClassWithDependencies(injector: injector) objectWithDependencies?.injectDependencies(injector: injector) } it("should not have object conforming to protocol injected") { expect(objectWithDependencies.objectConformingToProtocol).notTo(beNil()) } it("should not have empty swift object injected") { expect(objectWithDependencies.emptySwiftObject).notTo(beNil()) } it("should have injectable object injected") { expect(objectWithDependencies.injectableObject).notTo(beNil()) } it("should inject dependencies in injectable object") { expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue()) } it("should have injectable ObjC object injected") { expect(objectWithDependencies.injectableObjCObject).to(beAKindOf(InjectableObjCClass.self)) } it("should inject dependencies in injectable ObjC object") { expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue()) } it("should have ObjC object injected") { expect(objectWithDependencies.objCObject).to(beAKindOf(ObjCClass.self)) } } } } } }
e9433cb933281c19b167687cfce76968
48.943604
151
0.509874
false
false
false
false
erhoffex/SwiftAnyPic
refs/heads/master
SwiftAnyPic/PAPWelcomeViewController.swift
cc0-1.0
3
import UIKit import Synchronized import ParseFacebookUtils class PAPWelcomeViewController: UIViewController, PAPLogInViewControllerDelegate { private var _presentedLoginViewController: Bool = false private var _facebookResponseCount: Int = 0 private var _expectedFacebookResponseCount: Int = 0 private var _profilePicData: NSMutableData? = nil // MARK:- UIViewController override func loadView() { let backgroundImageView: UIImageView = UIImageView(frame: UIScreen.mainScreen().bounds) backgroundImageView.image = UIImage(named: "Default.png") self.view = backgroundImageView } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if PFUser.currentUser() == nil { presentLoginViewController(false) return } // Present Anypic UI (UIApplication.sharedApplication().delegate as! AppDelegate).presentTabBarController() // Refresh current user with server side data -- checks if user is still valid and so on _facebookResponseCount = 0 PFUser.currentUser()?.fetchInBackgroundWithTarget(self, selector: Selector("refreshCurrentUserCallbackWithResult:error:")) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK:- PAPWelcomeViewController func presentLoginViewController(animated: Bool) { if _presentedLoginViewController { return } _presentedLoginViewController = true let loginViewController = PAPLogInViewController() loginViewController.delegate = self presentViewController(loginViewController, animated: animated, completion: nil) } // MARK:- PAPLoginViewControllerDelegate func logInViewControllerDidLogUserIn(logInViewController: PAPLogInViewController) { if _presentedLoginViewController { _presentedLoginViewController = false self.dismissViewControllerAnimated(true, completion: nil) } } // MARK:- () func processedFacebookResponse() { // Once we handled all necessary facebook batch responses, save everything necessary and continue synchronized(self) { _facebookResponseCount++; if (_facebookResponseCount != _expectedFacebookResponseCount) { return } } _facebookResponseCount = 0; print("done processing all Facebook requests") PFUser.currentUser()!.saveInBackgroundWithBlock { (succeeded, error) in if !succeeded { print("Failed save in background of user, \(error)") } else { print("saved current parse user") } } } func refreshCurrentUserCallbackWithResult(refreshedObject: PFObject, error: NSError?) { // This fetches the most recent data from FB, and syncs up all data with the server including profile pic and friends list from FB. // A kPFErrorObjectNotFound error on currentUser refresh signals a deleted user if error != nil && error!.code == PFErrorCode.ErrorObjectNotFound.rawValue { print("User does not exist.") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } let session: FBSession = PFFacebookUtils.session()! if !session.isOpen { print("FB Session does not exist, logout") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } if session.accessTokenData.userID == nil { print("userID on FB Session does not exist, logout") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } guard let currentParseUser: PFUser = PFUser.currentUser() else { print("Current Parse user does not exist, logout") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } let facebookId = currentParseUser.objectForKey(kPAPUserFacebookIDKey) as? String if facebookId == nil || facebookId!.length == 0 { // set the parse user's FBID currentParseUser.setObject(session.accessTokenData.userID, forKey: kPAPUserFacebookIDKey) } if PAPUtility.userHasValidFacebookData(currentParseUser) == false { print("User does not have valid facebook ID. PFUser's FBID: \(currentParseUser.objectForKey(kPAPUserFacebookIDKey)), FBSessions FBID: \(session.accessTokenData.userID). logout") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } // Finished checking for invalid stuff // Refresh FB Session (When we link up the FB access token with the parse user, information other than the access token string is dropped // By going through a refresh, we populate useful parameters on FBAccessTokenData such as permissions. PFFacebookUtils.session()!.refreshPermissionsWithCompletionHandler { (session, error) in if (error != nil) { print("Failed refresh of FB Session, logging out: \(error)") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } // refreshed print("refreshed permissions: \(session)") self._expectedFacebookResponseCount = 0 let permissions: NSArray = session.accessTokenData.permissions // FIXME: How to use "contains" in Swift Array? Replace the NSArray with Swift array if permissions.containsObject("public_profile") { // Logged in with FB // Create batch request for all the stuff let connection = FBRequestConnection() self._expectedFacebookResponseCount++ connection.addRequest(FBRequest.requestForMe(), completionHandler: { (connection, result, error) in if error != nil { // Failed to fetch me data.. logout to be safe print("couldn't fetch facebook /me data: \(error), logout") (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() return } if let facebookName = result["name"] as? String where facebookName.length > 0 { currentParseUser.setObject(facebookName, forKey: kPAPUserDisplayNameKey) } self.processedFacebookResponse() }) // profile pic request self._expectedFacebookResponseCount++ connection.addRequest(FBRequest(graphPath: "me", parameters: ["fields": "picture.width(500).height(500)"], HTTPMethod: "GET"), completionHandler: { (connection, result, error) in if error == nil { // result is a dictionary with the user's Facebook data // FIXME: Really need to be this ugly??? // let userData = result as? [String : [String : [String : String]]] // let profilePictureURL = NSURL(string: userData!["picture"]!["data"]!["url"]!) // // Now add the data to the UI elements // let profilePictureURLRequest: NSURLRequest = NSURLRequest(URL: profilePictureURL!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10.0) // Facebook profile picture cache policy: Expires in 2 weeks // NSURLConnection(request: profilePictureURLRequest, delegate: self) if let userData = result as? [NSObject: AnyObject] { if let picture = userData["picture"] as? [NSObject: AnyObject] { if let data = picture["data"] as? [NSObject: AnyObject] { if let profilePictureURL = data["url"] as? String { // Now add the data to the UI elements let profilePictureURLRequest: NSURLRequest = NSURLRequest(URL: NSURL(string: profilePictureURL)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10.0) // Facebook profile picture cache policy: Expires in 2 weeks NSURLConnection(request: profilePictureURLRequest, delegate: self) } } } } } else { print("Error getting profile pic url, setting as default avatar: \(error)") let profilePictureData: NSData = UIImagePNGRepresentation(UIImage(named: "AvatarPlaceholder.png")!)! PAPUtility.processFacebookProfilePictureData(profilePictureData) } self.processedFacebookResponse() }) if permissions.containsObject("user_friends") { // Fetch FB Friends + me self._expectedFacebookResponseCount++ connection.addRequest(FBRequest.requestForMyFriends(), completionHandler: { (connection, result, error) in print("processing Facebook friends") if error != nil { // just clear the FB friend cache PAPCache.sharedCache.clear() } else { let data = result.objectForKey("data") as? NSArray let facebookIds: NSMutableArray = NSMutableArray(capacity: data!.count) for friendData in data! { if let facebookId = friendData["id"] { facebookIds.addObject(facebookId!) } } // cache friend data PAPCache.sharedCache.setFacebookFriends(facebookIds) if currentParseUser.objectForKey(kPAPUserFacebookFriendsKey) != nil { currentParseUser.removeObjectForKey(kPAPUserFacebookFriendsKey) } if currentParseUser.objectForKey(kPAPUserAlreadyAutoFollowedFacebookFriendsKey) != nil { (UIApplication.sharedApplication().delegate as! AppDelegate).autoFollowUsers() } } self.processedFacebookResponse() }) } connection.start() } else { let profilePictureData: NSData = UIImagePNGRepresentation(UIImage(named: "AvatarPlaceholder.png")!)! PAPUtility.processFacebookProfilePictureData(profilePictureData) PAPCache.sharedCache.clear() currentParseUser.setObject("Someone", forKey: kPAPUserDisplayNameKey) self._expectedFacebookResponseCount++ self.processedFacebookResponse() } } } // MARK:- NSURLConnectionDataDelegate func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { _profilePicData = NSMutableData() } func connection(connection: NSURLConnection, didReceiveData data: NSData) { _profilePicData!.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection) { PAPUtility.processFacebookProfilePictureData(_profilePicData!) } // MARK:- NSURLConnectionDelegate func connection(connection: NSURLConnection, didFailWithError error: NSError) { print("Connection error downloading profile pic data: \(error)") } }
0f50b1fab896d05393096fa91070827c
47.673152
282
0.585019
false
false
false
false
Oscareli98/Moya
refs/heads/master
Demo/Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Switch.swift
mit
3
// // Switch.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Switch_<O: ObserverType> : Sink<O>, ObserverType { typealias Element = Observable<O.Element> typealias Parent = Switch<O.Element> typealias SwitchState = ( subscription: SingleAssignmentDisposable, innerSubscription: SerialDisposable, stopped: Bool, latest: Int, hasLatest: Bool ) let parent: Parent var lock = NSRecursiveLock() var switchState: SwitchState init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent self.switchState = ( subscription: SingleAssignmentDisposable(), innerSubscription: SerialDisposable(), stopped: false, latest: 0, hasLatest: false ) super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = self.parent.sources.subscribeSafe(self) let switchState = self.switchState switchState.subscription.disposable = subscription return CompositeDisposable(switchState.subscription, switchState.innerSubscription) } func on(event: Event<Element>) { switch event { case .Next(let observable): let latest: Int = self.lock.calculateLocked { self.switchState.hasLatest = true self.switchState.latest = self.switchState.latest + 1 return self.switchState.latest } let d = SingleAssignmentDisposable() self.switchState.innerSubscription.setDisposable(d) let observer = SwitchIter(parent: self, id: latest, _self: d) let disposable = observable.value.subscribeSafe(observer) d.disposable = disposable case .Error(let error): self.lock.performLocked { trySendError(observer, error) self.dispose() } case .Completed: self.lock.performLocked { self.switchState.stopped = true self.switchState.subscription.dispose() if !self.switchState.hasLatest { trySendCompleted(observer) self.dispose() } } } } } class SwitchIter<O: ObserverType> : ObserverType { typealias Element = O.Element typealias Parent = Switch_<O> let parent: Parent let id: Int let _self: Disposable init(parent: Parent, id: Int, _self: Disposable) { self.parent = parent self.id = id self._self = _self } func on(event: Event<Element>) { return parent.lock.calculateLocked { state in let switchState = self.parent.switchState switch event { case .Next: break case .Error: fallthrough case .Completed: self._self.dispose() } if switchState.latest != self.id { return } let observer = self.parent.observer switch event { case .Next: trySend(observer, event) case .Error: trySend(observer, event) self.parent.dispose() case .Completed: parent.switchState.hasLatest = false if switchState.stopped { trySend(observer, event) self.parent.dispose() } } } } } class Switch<Element> : Producer<Element> { let sources: Observable<Observable<Element>> init(sources: Observable<Observable<Element>>) { self.sources = sources } override func run<O : ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Switch_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
659e2038f4fc54f430d4fd7f03640933
29.276596
146
0.549672
false
true
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/CenterTopMiddle.Individual.swift
apache-2.0
1
// // CenterTopMiddle.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct CenterTopMiddle { let center: LayoutElement.Horizontal let top: LayoutElement.Vertical let middle: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.CenterTopMiddle { private func makeFrame(center: Float, top: Float, middle: Float, width: Float) -> Rect { let x = center - width.half let y = top let height = (middle - top).double let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.CenterTopMiddle: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let center = self.center.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let middle = self.middle.evaluated(from: parameters) let height = (middle - top).double let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(center: center, top: top, middle: middle, width: width) } }
c33879aa541343dfc92ee249ad48c929
22.263158
115
0.717195
false
false
false
false
iamyuiwong/swift-sqlite
refs/heads/master
sqlite/SQLiteValueType.swift
lgpl-3.0
1
// SQLiteValueType.swift // 15/10/12. import Foundation /* sqlite 3 #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 */ public enum SQLiteValueType: Int32 { public static func get (byValue v: Int32 = 3) -> SQLiteValueType { switch (v) { case 1: return INTEGER case 2: return FLOAT case 4: return BLOB case 5: return NULL case 3: fallthrough default: return TEXT } } case INTEGER = 1 case FLOAT = 2 case TEXT = 3 case BLOB = 4 case NULL = 5 case DATETIME = 6 }
59dee72acd67ab427665f1d1e1bdae42
13.170213
67
0.66015
false
false
false
false
corchwll/amos-ss15-proj5_ios
refs/heads/master
MobileTimeAccounting/BusinessLogic/CSV/SessionsCSVExporter.swift
agpl-3.0
1
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation class SessionsCSVExporter { let csvBuilder = CSVBuilder() let dateFormatter = NSDateFormatter() let calendar = NSCalendar.currentCalendar() var month = 0 var year = 0 var projects = [Project]() var sessions = [[Session]]() /* Constructor, setting up date formatter. @methodtype Constructor @pre Date formatter has been initialized @post Date formatter is set up */ init() { dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.locale = NSLocale(localeIdentifier: "en_US") } /* Exports all sessions of a given month in a given year as csv file. @methodtype Helper @pre Valid values for month (>0) and year @post Returns csv file as NSData */ func exportCSV(month: Int, year: Int)->NSData { self.month = month self.year = year let csvString = doExportCSV() return csvString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } /* Exports all sessions of a given month in a given year as csv string by using CSVBuilder. @methodtype Command @pre CSVBuilder has been initialized @post Returns csv string */ func doExportCSV()->String { setHeading() setProjectsRow() setSessionRows() return csvBuilder.build() } /* Sets heading of csv file like: 'profile_firstname','profile_lastname','month','year' @methodtype Command @pre Profile has been set @post Heading is set */ private func setHeading() { let profile = profileDAO.getProfile()! csvBuilder.addRow(profile.firstname, profile.lastname, String(month), String(year)) } /* Sets all active projects of the given month into a row like: '','project1','project2',... @methodtype Command @pre Active projects are available @post Projects are added into row */ private func setProjectsRow() { projects = projectDAO.getProjects(month, year: year) csvBuilder.addRow("") for project in projects { csvBuilder.addRowItem(1, rowItem: project.name) sessions.append(sessionDAO.getSessions(project, month: month, year: year)) } } /* Sets all dates of all session rows of the given month like: '1/1/2015','8' '1/2/2015','0' ... @methodtype Command @pre - @post All session rows are set */ private func setSessionRows() { var currentRow = 2 let startOfMonth = NSDate(month: month, year: year, calendar: calendar).startOfMonth()! let endOfMonth = NSDate(month: month, year: year, calendar: calendar).endOfMonth()! for var date = startOfMonth; date.timeIntervalSince1970 < endOfMonth.timeIntervalSince1970; date = date.dateByAddingDays(1)! { csvBuilder.addRow(dateFormatter.stringFromDate(date)) setSessionRow(date, rowIndex: currentRow) currentRow++ } } /* Sets accumulated times of all sessions into csv rows. @methodtype Command @pre - @post Accumulated times of all sessions are set */ private func setSessionRow(date: NSDate, rowIndex: Int) { for var columnIndex = 1; columnIndex <= sessions.count; ++columnIndex { var accumulatedTime = 0 for session in sessions[columnIndex-1] { if calendar.components(.CalendarUnitDay, fromDate: session.startTime).day == calendar.components(.CalendarUnitDay, fromDate: date).day { accumulatedTime += (Int(session.endTime.timeIntervalSince1970 - session.startTime.timeIntervalSince1970))/60/60 } } csvBuilder.setRowItem(rowIndex, rowItemIndex: columnIndex, rowItem: String(accumulatedTime)) } } }
418513d0b25293b9add17c048c5196be
30.306748
150
0.601137
false
false
false
false
elationfoundation/Reporta-iOS
refs/heads/master
IWMF/TableViewCell/CheckInDetailTableViewCell.swift
gpl-3.0
1
// // CheckInLocationTableViewCell.swift // IWMF // // // // import Foundation import UIKit class CheckInDetailTableViewCell: UITableViewCell, UITextViewDelegate { @IBOutlet weak var textView: UITextView! var identity : String! = "" var value : NSString! = "" var title : String! = "" override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func intialize() { textView.selectable = false if value != nil{ if value.length > 0{ self.textView.text = value as String self.textView.textColor = UIColor.blackColor() }else{ self.textView.text = title self.textView.textColor = UIColor.lightGrayColor() } }else{ self.textView.text = title self.textView.textColor = UIColor.lightGrayColor() } self.textView.font = Utility.setFont() } func textViewDidBeginEditing(textView: UITextView) { } func textViewDidEndEditing(textView: UITextView) { } }
205a5451f3203dcfc2e295b42ff2187b
23.96
75
0.573376
false
false
false
false
LNTUORG/LntuOnline-iOS-Swift
refs/heads/master
eduadmin/ShowWebViewController.swift
gpl-2.0
1
// // ShowWebViewController.swift // eduadmin // // Created by Li Jie on 10/20/15. // Copyright © 2015 PUPBOSS. All rights reserved. // import UIKit class ShowWebViewController: UIViewController, UIWebViewDelegate { var webUrl = "" // MARK: - Outlets @IBOutlet weak var goBackButton: UIBarButtonItem! @IBOutlet weak var goNextButton: UIBarButtonItem! @IBOutlet weak var webView: UIWebView! @IBOutlet weak var actionButton: UIBarButtonItem! // MARK: - Actions @IBAction func goBack(sender: UIBarButtonItem) { self.webView.goBack() } @IBAction func goNext(sender: UIBarButtonItem) { self.webView.goForward() } @IBAction func goToSafari(sender: UIBarButtonItem) { } override func viewDidLoad() { super.viewDidLoad() self.webView.loadRequest(NSURLRequest.init(URL: NSURL.init(string: self.webUrl)!)) if self.webUrl == Constants.NOTICE_URL { self.actionButton.enabled = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { print(error) } func webViewDidStartLoad(webView: UIWebView) { if self.webUrl == Constants.NOTICE_URL { MBProgressHUD.showMessage("点击右上角用 Safari 访问") } else { if self.webView.canGoBack { self.goBackButton.enabled = true } else { self.goBackButton.enabled = false } if self.webView.canGoForward { self.goNextButton.enabled = true } else { self.goNextButton.enabled = false } MBProgressHUD.showMessage(Constants.Notification.LOADING) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in MBProgressHUD.hideHUD() } } } func webViewDidFinishLoad(webView: UIWebView) { MBProgressHUD.hideHUD() } }
bd0c7c0aa14496a855f015ef7334fb9c
23.515152
130
0.548826
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/CacheController.swift
mit
1
import Foundation public enum CacheControllerError: Error { case unableToCreateBackgroundCacheContext case atLeastOneItemFailedInFileWriter(Error) case failureToGenerateItemResult case atLeastOneItemFailedInSync(Error) } public class CacheController { #if TEST public static var temporaryCacheURL: URL? = nil #endif static let cacheURL: URL = { #if TEST if let temporaryCacheURL = temporaryCacheURL { return temporaryCacheURL } #endif var url = FileManager.default.wmf_containerURL().appendingPathComponent("Permanent Cache", isDirectory: true) var values = URLResourceValues() values.isExcludedFromBackup = true do { try url.setResourceValues(values) } catch { return url } return url }() // todo: Settings hook, logout don't sync hook, etc. public static var totalCacheSizeInBytes: Int64 { return FileManager.default.sizeOfDirectory(at: cacheURL) } /// Performs any necessary migrations on the CacheController's internal storage static func setupCoreDataStack(_ completion: @escaping (NSManagedObjectContext?, CacheControllerError?) -> Void) { // Expensive file & db operations happen as a part of this migration, so async it to a non-main queue DispatchQueue.global(qos: .default).async { // Instantiating the moc will perform the migrations in CacheItemMigrationPolicy guard let moc = createCacheContext(cacheURL: cacheURL) else { completion(nil, .unableToCreateBackgroundCacheContext) return } // do a moc.perform in case anything else needs to be run before the context is ready moc.perform { DispatchQueue.main.async { completion(moc, nil) } } } } static func createCacheContext(cacheURL: URL) -> NSManagedObjectContext? { // create cacheURL directory do { try FileManager.default.createDirectory(at: cacheURL, withIntermediateDirectories: true, attributes: nil) } catch let error { assertionFailure("Error creating permanent cache: \(error)") return nil } // create ManagedObjectModel based on Cache.momd guard let modelURL = Bundle.wmf.url(forResource: "Cache", withExtension: "momd"), let model = NSManagedObjectModel(contentsOf: modelURL) else { assertionFailure("Failure to create managed object model") return nil } // create persistent store coordinator / persistent store let dbURL = cacheURL.appendingPathComponent("Cache.sqlite", isDirectory: false) let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) let options = [ NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true), NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true) ] do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: options) } catch { do { try FileManager.default.removeItem(at: dbURL) } catch { assertionFailure("Failure to remove old db file") } do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: options) } catch { assertionFailure("Failure to add persistent store to coordinator") return nil } } let cacheBackgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) cacheBackgroundContext.persistentStoreCoordinator = persistentStoreCoordinator return cacheBackgroundContext } public typealias ItemKey = String public typealias GroupKey = String public typealias UniqueKey = String // combo of item key + variant public typealias IndividualCompletionBlock = (FinalIndividualResult) -> Void public typealias GroupCompletionBlock = (FinalGroupResult) -> Void public struct ItemKeyAndVariant: Hashable { let itemKey: CacheController.ItemKey let variant: String? init?(itemKey: CacheController.ItemKey?, variant: String?) { guard let itemKey = itemKey else { return nil } self.itemKey = itemKey self.variant = variant } } public enum FinalIndividualResult { case success(uniqueKey: CacheController.UniqueKey) case failure(error: Error) } public enum FinalGroupResult { case success(uniqueKeys: [CacheController.UniqueKey]) case failure(error: Error) } let dbWriter: CacheDBWriting let fileWriter: CacheFileWriter let gatekeeper = CacheGatekeeper() init(dbWriter: CacheDBWriting, fileWriter: CacheFileWriter) { self.dbWriter = dbWriter self.fileWriter = fileWriter } public func add(url: URL, groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock) { if gatekeeper.shouldQueueAddCompletion(groupKey: groupKey) { gatekeeper.queueAddCompletion(groupKey: groupKey) { self.add(url: url, groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion) return } } else { gatekeeper.addCurrentlyAddingGroupKey(groupKey) } if gatekeeper.numberOfQueuedGroupCompletions(for: groupKey) > 0 { gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion) return } gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion) dbWriter.add(url: url, groupKey: groupKey) { [weak self] (result) in self?.finishDBAdd(groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion, result: result) } } public func cancelTasks(groupKey: String) { dbWriter.cancelTasks(for: groupKey) fileWriter.cancelTasks(for: groupKey) } public func cancelAllTasks() { dbWriter.cancelAllTasks() fileWriter.cancelAllTasks() } func shouldDownloadVariantForAllVariantItems(variant: String?, _ allVariantItems: [CacheController.ItemKeyAndVariant]) -> Bool { return dbWriter.shouldDownloadVariantForAllVariantItems(variant: variant, allVariantItems) } func finishDBAdd(groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock, result: CacheDBWritingResultWithURLRequests) { let groupCompleteBlock = { (groupResult: FinalGroupResult) in self.gatekeeper.runAndRemoveGroupCompletions(groupKey: groupKey, groupResult: groupResult) self.gatekeeper.removeCurrentlyAddingGroupKey(groupKey) self.gatekeeper.runAndRemoveQueuedRemoves(groupKey: groupKey) } switch result { case .success(let urlRequests): var successfulKeys: [CacheController.UniqueKey] = [] var failedKeys: [(CacheController.UniqueKey, Error)] = [] let group = DispatchGroup() for urlRequest in urlRequests { guard let uniqueKey = fileWriter.uniqueFileNameForURLRequest(urlRequest), let url = urlRequest.url else { continue } group.enter() if gatekeeper.numberOfQueuedIndividualCompletions(for: uniqueKey) > 0 { defer { group.leave() } gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion) continue } gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion) guard dbWriter.shouldDownloadVariant(urlRequest: urlRequest) else { group.leave() continue } fileWriter.add(groupKey: groupKey, urlRequest: urlRequest) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let response, let data): self.dbWriter.markDownloaded(urlRequest: urlRequest, response: response) { (result) in defer { group.leave() } let individualResult: FinalIndividualResult switch result { case .success: successfulKeys.append(uniqueKey) individualResult = FinalIndividualResult.success(uniqueKey: uniqueKey) case .failure(let error): failedKeys.append((uniqueKey, error)) individualResult = FinalIndividualResult.failure(error: error) } self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult) } self.finishFileSave(data: data, mimeType: response.mimeType, uniqueKey: uniqueKey, url: url) case .failure(let error): defer { group.leave() } failedKeys.append((uniqueKey, error)) let individualResult = FinalIndividualResult.failure(error: error) self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult) } } group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { let groupResult: FinalGroupResult if let error = failedKeys.first?.1 { groupResult = FinalGroupResult.failure(error: CacheControllerError.atLeastOneItemFailedInFileWriter(error)) } else { groupResult = FinalGroupResult.success(uniqueKeys: successfulKeys) } groupCompleteBlock(groupResult) } } case .failure(let error): let groupResult = FinalGroupResult.failure(error: error) groupCompleteBlock(groupResult) } } func finishFileSave(data: Data, mimeType: String?, uniqueKey: CacheController.UniqueKey, url: URL) { // hook to allow subclasses to do any additional work with data } public func remove(groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock) { if gatekeeper.shouldQueueRemoveCompletion(groupKey: groupKey) { gatekeeper.queueRemoveCompletion(groupKey: groupKey) { self.remove(groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion) return } } else { gatekeeper.addCurrentlyRemovingGroupKey(groupKey) } if gatekeeper.numberOfQueuedGroupCompletions(for: groupKey) > 0 { gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion) return } gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion) cancelTasks(groupKey: groupKey) let groupCompleteBlock = { (groupResult: FinalGroupResult) in self.gatekeeper.runAndRemoveGroupCompletions(groupKey: groupKey, groupResult: groupResult) self.gatekeeper.removeCurrentlyRemovingGroupKey(groupKey) self.gatekeeper.runAndRemoveQueuedAdds(groupKey: groupKey) } dbWriter.fetchKeysToRemove(for: groupKey) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let keys): var successfulKeys: [CacheController.UniqueKey] = [] var failedKeys: [(CacheController.UniqueKey, Error)] = [] let group = DispatchGroup() for key in keys { guard let uniqueKey = self.fileWriter.uniqueFileNameForItemKey(key.itemKey, variant: key.variant) else { continue } group.enter() if self.gatekeeper.numberOfQueuedIndividualCompletions(for: uniqueKey) > 0 { defer { group.leave() } self.gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion) continue } self.gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion) self.fileWriter.remove(itemKey: key.itemKey, variant: key.variant) { (result) in switch result { case .success: self.dbWriter.remove(itemAndVariantKey: key) { (result) in defer { group.leave() } var individualResult: FinalIndividualResult switch result { case .success: successfulKeys.append(uniqueKey) individualResult = FinalIndividualResult.success(uniqueKey: uniqueKey) case .failure(let error): failedKeys.append((uniqueKey, error)) individualResult = FinalIndividualResult.failure(error: error) } self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult) } case .failure(let error): failedKeys.append((uniqueKey, error)) let individualResult = FinalIndividualResult.failure(error: error) self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult) group.leave() } } } group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { if let error = failedKeys.first?.1 { let groupResult = FinalGroupResult.failure(error: CacheControllerError.atLeastOneItemFailedInFileWriter(error)) groupCompleteBlock(groupResult) return } self.dbWriter.remove(groupKey: groupKey, completion: { (result) in var groupResult: FinalGroupResult switch result { case .success: groupResult = FinalGroupResult.success(uniqueKeys: successfulKeys) case .failure(let error): groupResult = FinalGroupResult.failure(error: error) } groupCompleteBlock(groupResult) }) } case .failure(let error): let groupResult = FinalGroupResult.failure(error: error) groupCompleteBlock(groupResult) } } } }
65592013729e25965b3bcce162bd6434
40.958025
195
0.568587
false
false
false
false
pulsarSMB/TagView
refs/heads/master
TagView/Classes/TagButton.swift
mit
1
// // TagButton.swift // TagViewDemo // // Created by pulsar on 08.09.17. // Copyright © 2017 pulsar. All rights reserved. // import UIKit public class TagButton: UIButton { var style: ButtonStyles? { didSet { oldValue != nil ? setStyle() : nil } } convenience init(title: String, style: ButtonStyles) { self.init(type: .system) self.style = style self.setTitle(title, for: .normal) } public override func setTitle(_ title: String?, for state: UIControlState) { super.setTitle(title, for: state) setStyle() } private func setStyle() { guard let style = style else { return } self.backgroundColor = style.backgroundColor self.tintColor = style.tintColor self.titleLabel?.font = style.titleFont self.sizeToFit() self.frame.size.height = (self.titleLabel?.font.pointSize)! + style.margin let radius = self.frame.height * 0.5 * style.percentCornerRadius self.layer.masksToBounds = true self.layer.cornerRadius = radius self.frame.size.width += radius + style.margin } }
806baf653ab44e88ed9983b261232c56
22.933333
78
0.666667
false
false
false
false
MetalheadSanya/GtkSwift
refs/heads/master
src/AssistantPageType.swift
bsd-3-clause
1
// // AssistantPageType.swift // GTK-swift // // Created by Alexander Zalutskiy on 13.04.16. // // import CGTK public enum AssistantPageType: RawRepresentable { case Content, Intro, Confirm, Summary, Progress, Custom public typealias RawValue = GtkAssistantPageType public var rawValue: RawValue { switch self { case .Content: return GTK_ASSISTANT_PAGE_CONTENT case .Intro: return GTK_ASSISTANT_PAGE_INTRO case .Confirm: return GTK_ASSISTANT_PAGE_CONFIRM case .Summary: return GTK_ASSISTANT_PAGE_SUMMARY case .Progress: return GTK_ASSISTANT_PAGE_PROGRESS case .Custom: return GTK_ASSISTANT_PAGE_CUSTOM } } public init?(rawValue: RawValue) { switch rawValue { case GTK_ASSISTANT_PAGE_CONTENT: self = .Content case GTK_ASSISTANT_PAGE_INTRO: self = .Intro case GTK_ASSISTANT_PAGE_CONFIRM: self = .Confirm case GTK_ASSISTANT_PAGE_SUMMARY: self = .Summary case GTK_ASSISTANT_PAGE_PROGRESS: self = .Progress case GTK_ASSISTANT_PAGE_CUSTOM: self = .Custom default: return nil } } }
e19b71a0bababb0e5fb3e052b70d095f
19.882353
56
0.709859
false
false
false
false
Incipia/Goalie
refs/heads/master
Goalie/GoalieAccessory.swift
apache-2.0
1
// // GoalieAccessory.swift // Goalie // // Created by Gregory Klein on 3/28/16. // Copyright © 2016 Incipia. All rights reserved. // import Foundation enum GoalieAccessory { case bricks, weight, jumprope, waterBottle, clock, plant, soda, homeWindow, workClock, computer, lamp, workWindow, unknown func drawRect(_ frame: CGRect, priority: TaskPriority) { switch self { case .bricks: BricksAccessoryKit.drawWithFrame(frame, priority: priority) case .weight: WeightAccessoryKit.drawWithFrame(frame, priority: priority) case .jumprope: JumpropeAccessoryKit.drawWithFrame(frame, priority: priority) case .waterBottle: WaterBottleAccessoryKit.drawWithFrame(frame, priority: priority) case .clock: ClockAccessoryKit.drawWithFrame(frame, priority: priority) case .plant: PlantAccessoryKit.drawWithFrame(frame, priority: priority) case .soda: SodaAccessoryKit.drawWithFrame(frame, priority: priority) case .homeWindow: HomeWindowAccessoryKit.drawWithFrame(frame, priority: priority) case .workClock: WorkClockAccessoryKit.drawWithFrame(frame, priority: priority) case .computer: ComputerAccessoryKit.drawWithFrame(frame, priority: priority) case .lamp: LampAccessoryKit.drawWithFrame(frame, priority: priority) case .workWindow: WorkWindowAccessoryKit.drawWithFrame(frame, priority: priority) case .unknown: _drawPurpleRect(frame) } } fileprivate func _drawPurpleRect(_ rect: CGRect) { UIColor.purple.setFill() UIRectFill(rect) } } extension CGSize { init(accessory: GoalieAccessory) { var size: (w: Int, h: Int) switch accessory { case .bricks: size = (79, 40) case .weight: size = (60, 30) case .jumprope: size = (36, 58) case .waterBottle: size = (22, 40) case .clock: size = (42, 44) case .plant: size = (26, 54) case .soda: size = (22, 36) case .homeWindow: size = (58, 56) case .workClock: size = (42, 42) case .computer: size = (70, 39) case .lamp: size = (42, 48) case .workWindow: size = (77, 50) case .unknown: size = (100, 100) } self.init(width: size.w, height: size.h) } }
c8fac30c82e88ccb506f0f4579bc5c3b
33.890625
125
0.673533
false
false
false
false
LFL2018/swiftSmpleCode
refs/heads/master
playground_Code/MapAndFlatMap.playground/Contents.swift
mit
1
// 6.12 2016 LFL //map 和 flatMap //:swift3后,将flatten()重命名为joined() import UIKit /// map let numberArrarys = [1,2,3,4,5,6] let resultNumbers = numberArrarys.map { $0 + 2} /** * @brief map 方法接受一个闭包作为参数, 然后它会遍历整个 numbers 数组,并对数组中每一个元素执行闭包中定义的操作。 相当于对数组中的所有元素做了一个映射 func map<T>(transform: (Self.Generator.Element) -> T) rethrows -> [T] Self.Generator.Element :当前元素的类型 注意:这个闭包的返回值,是可以和传递进来的值不同 */ print("map latter\(resultNumbers)") let resultString = numberArrarys.map { "LFL->\($0)" } print(resultString) // resultString.dynamicType // String数组 ///flatMap let flatNumber = numberArrarys.flatMap{$0 + 2} print(flatNumber) // 和map一样 // 区别 let numbersCompound = [[1,2,3],[4,5,6]]; var res = numbersCompound.map { $0.map{ $0 + 2 } } /** 这个调用实际上是遍历了这里两个数组元素 [1,2,3] 和 [4,5,6]。 因为这两个元素依然是数组,所以我们可以对他们再次调用 map 函数:$0.map{ $0 + 2 }。 这个内部的调用最终将数组中所有的元素加 2 */ // [[3, 4, 5], [6, 7, 8]] var flatRes = numbersCompound.flatMap { $0.map{ $0 + 2 } } /** flatMap 依然会遍历数组的元素,并对这些元素执行闭包中定义的操作。 但唯一不同的是,它对最终的结果进行了所谓的 "降维" 操作。 本来原始数组是一个二维的, 但经过 flatMap 之后,它变成一维的了。 */ // [3, 4, 5, 6, 7, 8] 降为一唯数组 /** 1.和 map 不同, flatMap 有两个重载 func flatMap<S : SequenceType>(transform: (Self.Generator.Element) -> S) -> [S.Generator.Element] flatMap的闭包接受的是数组的元素,但返回SequenceType 类型,也就是另外一个数组。 我们传入给 flatMap 一个闭包 $0.map{ $0 + 2 } , 这个闭包中,又对 $0 调用了 map 方法, 从 map 方法的定义中我们能够知道,它返回的还是一个集合类型,也就是 SequenceType。 所以我们这个 flatMap 的调用对应的就是第二个重载形式 */ //查阅源码 /** 文件位置: swift/stdlib/public/core/SequenceAlgorithms.swift.gyb extension Sequence { public func flatMap<S : Sequence>( @noescape transform: (${GElement}) throws -> S ) rethrows -> [S.${GElement}] { var result: [S.${GElement}] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } 1.对遍历的每一个元素调用try transform(element)。 transform 函数就是我们传递进来的闭包 2.然后将闭包的返回值通过 result.append(contentsOf:) 函数添加到 result 数组中。 2.1 名词简单说就是将一个集合中的所有元素,添加到另一个集合。 } */ // 2 func flatMap<T>(transform: (Self.Generator.Element) -> T?) -> [T] /** 它的闭包接收的是 Self.Generator.Element 类型, 返回的是一个 T? 。 我们都知道,在 Swift 中类型后面跟随一个 ?, 代表的是 Optional 值。 也就是说这个重载中接收的闭包返回的是一个 Optional 值。 更进一步来说,就是闭包可以返回 nil */ let optionalArray: [String?] = ["AA", nil, "BB", "CC"]; var optionalResult = optionalArray.flatMap{ $0 } // ["AA", "BB", "CC"] //而使用 print 函数输出 flatMap 的结果集时,会得到这样的输出: //["AA", "BB", "CC"] //也就是说原始数组的类型是 [String?] 而 flatMap 调用后变成了 [String]。 这也是 flatMap 和 map 的一个重大区别 //适用;过滤无效数据 var imageNames = ["1.png", "2.png", "nil.png"]; imageNames.flatMap{ UIImage(named: $0) } //查阅源码 /** * 依然是遍历所有元素,并应用 try transform(element) 闭包的调用, 但关键一点是,这里面用到了 if let 语句, 对那些只有解包成功的元素,才会添加到结果集中: if let newElement = try transform(element) { result.append(newElement) } */ // let numbers_1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let joined = numbers_1.joined(separator: [-1, -2]) print(Array(joined))
ca3566ab001f08126828910dcecd88c4
26.198113
145
0.677072
false
false
false
false
ustwo/mongolabkit-swift
refs/heads/master
MongoLabKit/MongoLabKitTests/DocumentsServiceTests.swift
mit
1
// // MongoLabKitTests.swift // MongoLabKitTests // // Created by luca strazzullo on 18/05/16. // // import XCTest @testable import MongoLabKit class MongoLabKit_DocumentsService_iOSTests: XCTestCase { private var service: DocumentsService? func testLoadDocuments() { let mockConfiguration = MongoLabApiV1Configuration(databaseName: "fakeName", apiKey: "fakeApiKey") let response = [["_id": ["$oid": "5743ab370a00b27cd1d10c92"]]] let mockResult = MongoLabClient.Result.success(response: response as AnyObject) loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) { result in switch result { case let .Success(response): XCTAssertEqual(response.first?.id, "5743ab370a00b27cd1d10c92") case let .Failure(error): XCTFail(error.description()) } } } func testLoadDocumentsWithParsingError() { let mockConfiguration = MongoLabApiV1Configuration(databaseName: "fakeName", apiKey: "fakeApiKey") let response = [["$oid": "5743ab370a00b27cd1d10c92"]] let mockResult = MongoLabClient.Result.success(response: response as AnyObject) loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) { result in switch result { case .Success: XCTFail() case let .Failure(error): XCTAssertEqual(error.description(), MongoLabError.parserError.description()) } } } func testLoadDocumentsWithConfigurationError() { let mockConfiguration = MongoLabApiV1Configuration(databaseName: "", apiKey: "") let response = [["$oid": "5743ab370a00b27cd1d10c92"]] let mockResult = MongoLabClient.Result.success(response: response as AnyObject) loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) { result in switch result { case .Success: XCTFail() case let .Failure(error): XCTAssertEqual(error.description(), RequestError.configuration.description()) } } } // MARK: - Private helper methods private func loadDocumentsWithMongoLab(mockResult: MongoLabClient.Result, configuration: MongoLabApiV1Configuration, completion: @escaping MockDocumentServiceDelegate.Completion) { let asynchronousExpectation = expectation(description: "asynchronous") let mockClient = MockMongoLabClient(result: mockResult) let mockDelegate = MockDocumentServiceDelegate() { result in asynchronousExpectation.fulfill() completion(result) } loadDocumentsWith(client: mockClient, configuration: configuration, delegate: mockDelegate) waitForExpectations(timeout: 10, handler: nil) } private func loadDocumentsWith(client: MongoLabClient, configuration: MongoLabApiV1Configuration, delegate: ServiceDelegate) { service = DocumentsService(client: client, configuration: configuration, delegate: delegate) service?.loadDocuments(for: "collection") } // MARK: - Mocked client private class MockMongoLabClient: MongoLabClient { var result: MongoLabClient.Result init (result: MongoLabClient.Result) { self.result = result } override func perform(_ request: URLRequest, completion: @escaping MongoLabClient.Completion) -> URLSessionTask { completion(result) return URLSessionTask() } } // MARK: - Mocked delegate class MockDocumentServiceDelegate: ServiceDelegate { enum Result { case Success(response: Documents) case Failure(error: ErrorDescribable) } typealias Completion = (_ result: Result) -> () let completion: Completion func serviceWillLoad<DataType>(_ service: Service<DataType>) {} func service<DataType>(_ service: Service<DataType>, didLoad data: DataType) { if let documents = data as? Documents { completion(Result.Success(response: documents)) } } func service<DataType>(_ service: Service<DataType>, didFailWith error: ErrorDescribable) { completion(Result.Failure(error: error)) } init(completion: @escaping Completion) { self.completion = completion } } }
3661b0aead5ae64ee3439da1235bdcfd
27.8125
184
0.641432
false
true
false
false