Skip to content

Implementing (initial) of Stream and InputStream. #442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CoreFoundation/Base.subproj/ForFoundationOnly.h
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ CF_EXPORT Boolean _CFRunLoopFinished(CFRunLoopRef rl, CFStringRef mode);
CF_EXPORT CFTypeRef _CFRunLoopGet2(CFRunLoopRef rl);

CF_EXPORT CFIndex _CFStreamInstanceSize(void);
CF_EXPORT CFReadStreamRef CFReadStreamCreateWithData(CFAllocatorRef alloc, CFDataRef data);

#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
typedef struct {
Expand Down
4 changes: 4 additions & 0 deletions Foundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
0383A1751D2E558A0052E5D1 /* TestNSStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0383A1741D2E558A0052E5D1 /* TestNSStream.swift */; };
294E3C1D1CC5E19300E4F44C /* TestNSAttributedString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */; };
2EBE67A51C77BF0E006583D5 /* TestNSDateFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EBE67A31C77BF05006583D5 /* TestNSDateFormatter.swift */; };
528776141BF2629700CB0090 /* FoundationErrors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 522C253A1BF16E1600804FC6 /* FoundationErrors.swift */; };
Expand Down Expand Up @@ -419,6 +420,7 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
0383A1741D2E558A0052E5D1 /* TestNSStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSStream.swift; sourceTree = "<group>"; };
22B9C1E01C165D7A00DECFF9 /* TestNSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDate.swift; sourceTree = "<group>"; };
294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSAttributedString.swift; sourceTree = "<group>"; };
2EBE67A31C77BF05006583D5 /* TestNSDateFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDateFormatter.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1276,6 +1278,7 @@
5B40F9F11C125187000E72E3 /* TestNSXMLParser.swift */,
CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */,
5B6F17961C48631C00935030 /* TestUtils.swift */,
0383A1741D2E558A0052E5D1 /* TestNSStream.swift */,
);
name = Tests;
sourceTree = "<group>";
Expand Down Expand Up @@ -2086,6 +2089,7 @@
5B13B34E1C582D4C00651CE2 /* TestNSXMLDocument.swift in Sources */,
5B13B32B1C582D4C00651CE2 /* TestNSData.swift in Sources */,
5B13B34C1C582D4C00651CE2 /* TestNSURLResponse.swift in Sources */,
0383A1751D2E558A0052E5D1 /* TestNSStream.swift in Sources */,
5B13B3481C582D4C00651CE2 /* TestNSTimer.swift in Sources */,
5B13B32D1C582D4C00651CE2 /* TestNSDictionary.swift in Sources */,
5B13B3261C582D4C00651CE2 /* TestNSAffineTransform.swift in Sources */,
Expand Down
37 changes: 27 additions & 10 deletions Foundation/NSStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

import CoreFoundation
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be for all operating systems not just Linux


extension Stream {
public struct PropertyKey : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
Expand Down Expand Up @@ -60,17 +62,17 @@ public func <(lhs: Stream.PropertyKey, rhs: Stream.PropertyKey) -> Bool {
// NSStream is an abstract class encapsulating the common API to NSInputStream and NSOutputStream.
// Subclassers of NSInputStream and NSOutputStream must also implement these methods.
public class Stream: NSObject {

public override init() {

}

public func open() {
NSUnimplemented()
NSRequiresConcreteImplementation()
}

public func close() {
NSUnimplemented()
NSRequiresConcreteImplementation()
}

public weak var delegate: StreamDelegate?
Expand All @@ -95,7 +97,7 @@ public class Stream: NSObject {
}

public var streamStatus: Status {
NSUnimplemented()
NSRequiresConcreteImplementation()
}

/*@NSCopying */public var streamError: NSError? {
Expand All @@ -106,9 +108,12 @@ public class Stream: NSObject {
// NSInputStream is an abstract class representing the base functionality of a read stream.
// Subclassers are required to implement these methods.
public class InputStream: Stream {

private var _stream: CFReadStream!

// reads up to length bytes into the supplied buffer, which must be at least of size len. Returns the actual number of bytes read.
public func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int {
NSUnimplemented()
return CFReadStreamRead(_stream, buffer, CFIndex(len._bridgeToObject()))
}

// returns in O(1) a pointer to the buffer in 'buffer' and by reference in 'len' how many bytes are available. This buffer is only valid until the next stream operation. Subclassers may return NO for this if it is not appropriate for the stream type. This may return NO if the buffer is not available.
Expand All @@ -118,19 +123,31 @@ public class InputStream: Stream {

// returns YES if the stream has bytes available or if it impossible to tell without actually doing the read.
public var hasBytesAvailable: Bool {
NSUnimplemented()
return CFReadStreamHasBytesAvailable(_stream)
}

public init(data: Data) {
NSUnimplemented()
_stream = CFReadStreamCreateWithData(kCFAllocatorSystemDefault, data._cfObject)
}

public init?(url: URL) {
NSUnimplemented()
_stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url._cfObject)
}

public convenience init?(fileAtPath path: String) {
NSUnimplemented()
self.init(url: URL(fileURLWithPath: path))
}

public override func open() {
CFReadStreamOpen(_stream)
}

public override func close() {
CFReadStreamClose(_stream)
}

public override var streamStatus: Status {
return Stream.Status(rawValue: UInt(CFReadStreamGetStatus(_stream)))!
}
}

Expand Down
145 changes: 145 additions & 0 deletions TestFoundation/TestNSStream.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif

class TestNSStream : XCTestCase {
static var allTests: [(String, (TestNSStream) -> () throws -> Void)] {
return [
("test_InputStreamWithData", test_InputStreamWithData),
("test_InputStreamWithUrl", test_InputStreamWithUrl),
("test_InputStreamWithFile", test_InputStreamWithFile),
("test_InputStreamHasBytesAvailable", test_InputStreamHasBytesAvailable),
("test_InputStreamInvalidPath", test_InputStreamInvalidPath),
]
}

func test_InputStreamWithData(){
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
let dataStream: InputStream = InputStream(data: messageData)
XCTAssertEqual(Stream.Status.notOpen, dataStream.streamStatus)
dataStream.open()
XCTAssertEqual(Stream.Status.open, dataStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if dataStream.hasBytesAvailable {
let result: Int = dataStream.read(&buffer, maxLength: buffer.count)
dataStream.close()
XCTAssertEqual(Stream.Status.closed, dataStream.streamStatus)
if(result > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
}
}

func test_InputStreamWithUrl() {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
//Initialiser with url
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let url = URL(fileURLWithPath: testFile!)
let urlStream: InputStream = InputStream(url: url)!
XCTAssertEqual(Stream.Status.notOpen, urlStream.streamStatus)
urlStream.open()
XCTAssertEqual(Stream.Status.open, urlStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if urlStream.hasBytesAvailable {
let result :Int = urlStream.read(&buffer, maxLength: buffer.count)
urlStream.close()
XCTAssertEqual(Stream.Status.closed, urlStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0) {
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
}
removeTestFile(testFile!)
} else {
XCTFail("Unable to create temp file")
}
}

func test_InputStreamWithFile() {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
//Initialiser with file
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let fileStream: InputStream = InputStream(fileAtPath: testFile!)!
XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
fileStream.open()
XCTAssertEqual(Stream.Status.open, fileStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if fileStream.hasBytesAvailable {
let result: Int = fileStream.read(&buffer, maxLength: buffer.count)
fileStream.close()
XCTAssertEqual(Stream.Status.closed, fileStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
}
removeTestFile(testFile!)
} else {
XCTFail("Unable to create temp file")
}
}

func test_InputStreamHasBytesAvailable() {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
let stream: InputStream = InputStream(data: messageData)
var buffer = [UInt8](repeating: 0, count: 20)
stream.open()
XCTAssertTrue(stream.hasBytesAvailable)
_ = stream.read(&buffer, maxLength: buffer.count)
XCTAssertFalse(stream.hasBytesAvailable)
}

func test_InputStreamInvalidPath() {
let fileStream: InputStream = InputStream(fileAtPath: "/tmp/file.txt")!
XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
fileStream.open()
XCTAssertEqual(Stream.Status.error, fileStream.streamStatus)
}

private func createTestFile(_ path: String,_contents: Data) -> String? {
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().UUIDString + "/"
do {
try FileManager.default().createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
if FileManager.default().createFile(atPath: tempDir + "/" + path, contents: _contents, attributes: nil) {
return tempDir + path
} else {
return nil
}
} catch _ {
return nil
}

}

private func removeTestFile(_ location: String) {
do {
try FileManager.default().removeItem(atPath: location)
} catch _ {

}
}
}


1 change: 1 addition & 0 deletions TestFoundation/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ XCTMain([
testCase(TestNSRunLoop.allTests),
testCase(TestNSScanner.allTests),
testCase(TestNSSet.allTests),
testCase(TestNSStream.allTests),
testCase(TestNSString.allTests),
// testCase(TestNSThread.allTests),
testCase(TestNSTask.allTests),
Expand Down