Skip to content

Commit 58e40e1

Browse files
committed
Merge branch 'master' of github.com:hpux735/swift-corelibs-foundation
2 parents 6395787 + aa25b1c commit 58e40e1

23 files changed

+741
-44
lines changed

CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,10 @@ struct _NSXMLParserBridge {
177177
const unsigned char *SystemID);
178178
};
179179

180+
struct _NSRunLoop {
181+
_Nonnull CFTypeRef (*_Nonnull _new)(CFRunLoopRef rl);
182+
};
183+
180184
struct _CFSwiftBridge {
181185
struct _NSObjectBridge NSObject;
182186
struct _NSArrayBridge NSArray;
@@ -188,6 +192,7 @@ struct _CFSwiftBridge {
188192
struct _NSStringBridge NSString;
189193
struct _NSMutableStringBridge NSMutableString;
190194
struct _NSXMLParserBridge NSXMLParser;
195+
struct _NSRunLoop NSRunLoop;
191196
};
192197

193198
__attribute__((__visibility__("hidden"))) extern struct _CFSwiftBridge __CFSwiftBridge;
@@ -264,6 +269,8 @@ extern void *_CFReallocf(void *ptr, size_t size);
264269

265270
CFHashCode CFStringHashNSString(CFStringRef str);
266271

272+
extern CFTypeRef _CFRunLoopGet2(CFRunLoopRef rl);
273+
267274
extern CFIndex __CFStringEncodeByteStream(CFStringRef string, CFIndex rangeLoc, CFIndex rangeLen, Boolean generatingExternalFile, CFStringEncoding encoding, uint8_t lossByte, UInt8 * _Nullable buffer, CFIndex max, CFIndex * _Nullable usedBufLen);
268275

269276
typedef unsigned char __cf_uuid[16];

CoreFoundation/RunLoop.subproj/CFRunLoop.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1526,7 +1526,12 @@ CF_PRIVATE void __CFFinalizeRunLoop(uintptr_t data) {
15261526
}
15271527
if (rl && CFRunLoopGetMain() != rl) { // protect against cooperative threads
15281528
if (NULL != rl->_counterpart) {
1529+
#if DEPLOYMENT_RUNTIME_SWIFT
1530+
extern void swift_release(void *);
1531+
swift_release((void *)rl->_counterpart);
1532+
#else
15291533
CFRelease(rl->_counterpart);
1534+
#endif
15301535
rl->_counterpart = NULL;
15311536
}
15321537
// purge all sources before deallocation
@@ -1549,6 +1554,12 @@ pthread_t _CFRunLoopGet1(CFRunLoopRef rl) {
15491554
CF_EXPORT CFTypeRef _CFRunLoopGet2(CFRunLoopRef rl) {
15501555
CFTypeRef ret = NULL;
15511556
__CFLock(&loopsLock);
1557+
#if DEPLOYMENT_RUNTIME_SWIFT
1558+
if (rl->_counterpart == NULL) {
1559+
CFTypeRef ns = __CFSwiftBridge.NSRunLoop._new(rl); // returns retained so we will claim ownership of that return value by just assigning (the release is balanced in the destruction of the CFRunLoop
1560+
rl->_counterpart = ns;
1561+
}
1562+
#endif
15521563
ret = rl->_counterpart;
15531564
__CFUnlock(&loopsLock);
15541565
return ret;

Foundation/NSArray.swift

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -393,13 +393,18 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS
393393
}
394394

395395
internal func sortedArrayFromRange(range: NSRange, options: NSSortOptions, usingComparator cmptr: NSComparator) -> [AnyObject] {
396+
// The sort options are not available. We use the Array's sorting algorithm. It is not stable neither concurrent.
397+
guard options.isEmpty else {
398+
NSUnimplemented()
399+
}
400+
396401
let count = self.count
397402
if range.length == 0 || count == 0 {
398403
return []
399404
}
400405

401406
return allObjects.sort { lhs, rhs in
402-
return cmptr(lhs, rhs) == .OrderedSame
407+
return cmptr(lhs, rhs) == .OrderedAscending
403408
}
404409
}
405410

@@ -412,22 +417,44 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS
412417
}
413418

414419
public func indexOfObject(obj: AnyObject, inSortedRange r: NSRange, options opts: NSBinarySearchingOptions, usingComparator cmp: NSComparator) -> Int {
415-
guard (r.location + r.length) <= count else {
416-
NSInvalidArgument("range \(r) extends beyond bounds [0 .. \(count - 1)]")
420+
let lastIndex = r.location + r.length - 1
421+
422+
// argument validation
423+
guard lastIndex < count else {
424+
let bounds = count == 0 ? "for empty array" : "[0 .. \(count - 1)]"
425+
NSInvalidArgument("range \(r) extends beyond bounds \(bounds)")
417426
}
418427

419428
if opts.contains(.FirstEqual) && opts.contains(.LastEqual) {
420429
NSInvalidArgument("both NSBinarySearching.FirstEqual and NSBinarySearching.LastEqual options cannot be specified")
421430
}
422431

432+
let searchForInsertionIndex = opts.contains(.InsertionIndex)
433+
434+
// fringe cases
435+
if r.length == 0 {
436+
return searchForInsertionIndex ? r.location : NSNotFound
437+
}
438+
439+
let leastObj = objectAtIndex(r.location)
440+
if cmp(obj, leastObj) == .OrderedAscending {
441+
return searchForInsertionIndex ? r.location : NSNotFound
442+
}
443+
444+
let greatestObj = objectAtIndex(lastIndex)
445+
if cmp(obj, greatestObj) == .OrderedDescending {
446+
return searchForInsertionIndex ? lastIndex + 1 : NSNotFound
447+
}
448+
449+
// common processing
423450
let firstEqual = opts.contains(.FirstEqual)
424451
let lastEqual = opts.contains(.LastEqual)
425452
let anyEqual = !(firstEqual || lastEqual)
426453

427454
var result = NSNotFound
428455
var indexOfLeastGreaterThanObj = NSNotFound
429456
var start = r.location
430-
var end = r.location + r.length - 1
457+
var end = lastIndex
431458

432459
loop: while start <= end {
433460
let middle = start + (end - start) / 2
@@ -459,18 +486,14 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS
459486
}
460487
}
461488

462-
guard opts.contains(.InsertionIndex) && lastEqual else {
489+
guard searchForInsertionIndex && lastEqual else {
463490
return result
464491
}
465492

466493
guard result == NSNotFound else {
467494
return result + 1
468495
}
469496

470-
guard indexOfLeastGreaterThanObj != NSNotFound else {
471-
return count
472-
}
473-
474497
return indexOfLeastGreaterThanObj
475498
}
476499

Foundation/NSDecimalNumber.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public class NSDecimalNumber : NSNumber {
8484
public func decimalNumberByRoundingAccordingToBehavior(behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() }
8585
// Round to the scale of the behavior.
8686

87-
public func compare(decimalNumber: NSNumber) -> NSComparisonResult { NSUnimplemented() }
87+
public override func compare(decimalNumber: NSNumber) -> NSComparisonResult { NSUnimplemented() }
8888
// compare two NSDecimalNumbers
8989

9090
public class func setDefaultBehavior(behavior: NSDecimalNumberBehaviors) { NSUnimplemented() }

Foundation/NSFileManager.swift

Lines changed: 103 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -191,20 +191,115 @@ public class NSFileManager : NSObject {
191191
}
192192
}
193193

194-
/* contentsOfDirectoryAtPath:error: returns an NSArray of NSStrings representing the filenames of the items in the directory. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. If the directory contains no items, this method will return the empty array.
194+
/**
195+
Performs a shallow search of the specified directory and returns the paths of any contained items.
195196

196-
This method replaces directoryContentsAtPath:
197+
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”) but it does return other hidden files (files that begin with a period character).
198+
199+
The order of the files in the returned array is undefined.
200+
201+
- Parameter path: The path to the directory whose contents you want to enumerate.
202+
203+
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
204+
205+
- Returns: An array of String each of which identifies a file, directory, or symbolic link contained in `path`. The order of the files returned is undefined.
197206
*/
198207
public func contentsOfDirectoryAtPath(path: String) throws -> [String] {
199-
NSUnimplemented()
208+
var contents : [String] = [String]()
209+
210+
let dir = opendir(path)
211+
212+
if dir == nil {
213+
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadNoSuchFileError.rawValue, userInfo: [NSFilePathErrorKey: path])
214+
}
215+
216+
defer {
217+
closedir(dir)
218+
}
219+
220+
var entry: UnsafeMutablePointer<dirent> = readdir(dir)
221+
222+
while entry != nil {
223+
if let entryName = withUnsafePointer(&entry.memory.d_name, { (ptr) -> String? in
224+
let int8Ptr = unsafeBitCast(ptr, UnsafePointer<Int8>.self)
225+
return String.fromCString(int8Ptr)
226+
}) {
227+
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
228+
if entryName != "." && entryName != ".." {
229+
contents.append(entryName)
230+
}
231+
}
232+
233+
entry = readdir(dir)
234+
}
235+
236+
return contents
200237
}
201238

202-
/* subpathsOfDirectoryAtPath:error: returns an NSArray of NSStrings representing the filenames of the items in the specified directory and all its subdirectories recursively. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. If the directory contains no items, this method will return the empty array.
203-
204-
This method replaces subpathsAtPath:
205-
*/
239+
/**
240+
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
241+
242+
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
243+
244+
Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time.
245+
246+
- Parameter path: The path of the directory to list.
247+
248+
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
249+
250+
- Returns: An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
251+
*/
206252
public func subpathsOfDirectoryAtPath(path: String) throws -> [String] {
207-
NSUnimplemented()
253+
var contents : [String] = [String]()
254+
255+
let dir = opendir(path)
256+
257+
if dir == nil {
258+
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadNoSuchFileError.rawValue, userInfo: [NSFilePathErrorKey: path])
259+
}
260+
261+
defer {
262+
closedir(dir)
263+
}
264+
265+
var entry = readdir(dir)
266+
267+
while entry != nil {
268+
if let entryName = withUnsafePointer(&entry.memory.d_name, { (ptr) -> String? in
269+
let int8Ptr = unsafeBitCast(ptr, UnsafePointer<Int8>.self)
270+
return String.fromCString(int8Ptr)
271+
}) {
272+
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
273+
if entryName != "." && entryName != ".." {
274+
contents.append(entryName)
275+
276+
if let entryType = withUnsafePointer(&entry.memory.d_type, { (ptr) -> Int32? in
277+
let int32Ptr = unsafeBitCast(ptr, UnsafePointer<UInt8>.self)
278+
return Int32(int32Ptr.memory)
279+
}) {
280+
#if os(OSX) || os(iOS)
281+
if entryType == DT_DIR {
282+
let subPath: String = path + "/" + entryName
283+
284+
let entries = try subpathsOfDirectoryAtPath(subPath)
285+
contents.appendContentsOf(entries.map({file in "\(entryName)/\(file)"}))
286+
}
287+
#elseif os(Linux)
288+
if Int(entryType) == DT_DIR {
289+
let subPath: String = path + "/" + entryName
290+
291+
let entries = try subpathsOfDirectoryAtPath(subPath)
292+
contents.appendContentsOf(entries.map({file in "\(entryName)/\(file)"}))
293+
}
294+
#endif
295+
}
296+
}
297+
}
298+
299+
entry = readdir(dir)
300+
}
301+
302+
return contents
208303
}
209304

210305
/* attributesOfItemAtPath:error: returns an NSDictionary of key/value pairs containing the attributes of the item (file, directory, symlink, etc.) at the path in question. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.

Foundation/NSGeometry.swift

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,50 @@ public func NSOffsetRect(aRect: NSRect, _ dX: CGFloat, _ dY: CGFloat) -> NSRect
485485
return result
486486
}
487487

488-
public func NSDivideRect(inRect: NSRect, _ slice: UnsafeMutablePointer<NSRect>, _ rem: UnsafeMutablePointer<NSRect>, _ amount: CGFloat, _ edge: NSRectEdge) { NSUnimplemented() }
488+
public func NSDivideRect(inRect: NSRect, _ slice: UnsafeMutablePointer<NSRect>, _ rem: UnsafeMutablePointer<NSRect>, _ amount: CGFloat, _ edge: NSRectEdge) {
489+
if NSIsEmptyRect(inRect) {
490+
slice.memory = NSZeroRect
491+
rem.memory = NSZeroRect
492+
return
493+
}
494+
495+
let width = NSWidth(inRect)
496+
let height = NSHeight(inRect)
497+
498+
switch (edge, amount) {
499+
case (.MinX, let amount) where amount > width:
500+
slice.memory = inRect
501+
rem.memory = NSMakeRect(NSMaxX(inRect), NSMinY(inRect), CGFloat(0.0), height)
502+
503+
case (.MinX, _):
504+
slice.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), amount, height)
505+
rem.memory = NSMakeRect(NSMaxX(slice.memory), NSMinY(inRect), NSMaxX(inRect) - NSMaxX(slice.memory), height)
506+
507+
case (.MinY, let amount) where amount > height:
508+
slice.memory = inRect
509+
rem.memory = NSMakeRect(NSMinX(inRect), NSMaxY(inRect), width, CGFloat(0.0))
510+
511+
case (.MinY, _):
512+
slice.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), width, amount)
513+
rem.memory = NSMakeRect(NSMinX(inRect), NSMaxY(slice.memory), width, NSMaxY(inRect) - NSMaxY(slice.memory))
514+
515+
case (.MaxX, let amount) where amount > width:
516+
slice.memory = inRect
517+
rem.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), CGFloat(0.0), height)
518+
519+
case (.MaxX, _):
520+
slice.memory = NSMakeRect(NSMaxX(inRect) - amount, NSMinY(inRect), amount, height)
521+
rem.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), NSMinX(slice.memory) - NSMinX(inRect), height)
522+
523+
case (.MaxY, let amount) where amount > height:
524+
slice.memory = inRect
525+
rem.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), width, CGFloat(0.0))
526+
527+
case (.MaxY, _):
528+
slice.memory = NSMakeRect(NSMinX(inRect), NSMaxY(inRect) - amount, width, amount)
529+
rem.memory = NSMakeRect(NSMinX(inRect), NSMinY(inRect), width, NSMinY(slice.memory) - NSMinY(inRect))
530+
}
531+
}
489532

490533
public func NSPointInRect(aPoint: NSPoint, _ aRect: NSRect) -> Bool {
491534
return NSMouseInRect(aPoint, aRect, true)

Foundation/NSHost.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,11 @@ public class NSHost : NSObject {
8484
if r != 0 {
8585
return
8686
}
87-
for var res: UnsafeMutablePointer<addrinfo> = res0; res != nil; res = res.memory.ai_next {
87+
var res: UnsafeMutablePointer<addrinfo> = res0
88+
while res != nil {
8889
let family = res.memory.ai_family
8990
if family != AF_INET && family != AF_INET6 {
91+
res = res.memory.ai_next
9092
continue
9193
}
9294
let sa_len: socklen_t = socklen_t((family == AF_INET6) ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))
@@ -101,6 +103,7 @@ public class NSHost : NSObject {
101103
lookupInfo(&_addresses, NI_NUMERICHOST)
102104
lookupInfo(&_names, NI_NAMEREQD)
103105
lookupInfo(&_names, NI_NOFQDN|NI_NAMEREQD)
106+
res = res.memory.ai_next
104107
}
105108

106109
freeaddrinfo(res0)

Foundation/NSIndexSet.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ public class NSMutableIndexSet : NSIndexSet {
556556
// Nothing to add
557557
return
558558
} else if range.location >= curRange.location && range.location <= curEnd && addEnd > curEnd {
559-
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(addEnd - curRange.location, curRange.location))
559+
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, addEnd - curRange.location))
560560
replacedRangeIndex = rangeIndex
561561
// Proceed to merging
562562
break

Foundation/NSNumber.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,10 @@ public class NSNumber : NSValue {
381381
public required convenience init(booleanLiteral value: Bool) {
382382
self.init(bool: value)
383383
}
384+
385+
public func compare(otherNumber: NSNumber) -> NSComparisonResult {
386+
return ._fromCF(CFNumberCompare(_cfObject, otherNumber._cfObject, nil))
387+
}
384388

385389
override internal var _cfTypeID: CFTypeID {
386390
return CFNumberGetTypeID()

Foundation/NSObjCRuntime.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public let NSNotFound: Int = Int.max
8080
fatalError("\(fn) is not yet implemented")
8181
}
8282

83-
@noreturn func NSInvalidArgument(message: String, method: String = __FUNCTION__) {
83+
@noreturn internal func NSInvalidArgument(message: String, method: String = __FUNCTION__) {
8484
fatalError("\(method): \(message)")
8585
}
8686

0 commit comments

Comments
 (0)