2
2
//
3
3
// This source file is part of the Swift.org open source project
4
4
//
5
- // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
5
+ // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
6
6
// Licensed under Apache License v2.0 with Runtime Library Exception
7
7
//
8
8
// See https://swift.org/LICENSE.txt for license information
@@ -27,45 +27,18 @@ import SwiftShims
27
27
/// - Returns: The string of characters read from standard input. If EOF has
28
28
/// already been reached when `readLine()` is called, the result is `nil`.
29
29
public func readLine( strippingNewline: Bool = true ) -> String ? {
30
- var linePtrVar : UnsafeMutablePointer < UInt8 > ?
31
- var readBytes = swift_stdlib_readLine_stdin ( & linePtrVar )
32
- if readBytes == - 1 {
33
- return nil
30
+ var utf8Start : UnsafeMutablePointer < UInt8 > ?
31
+ let utf8Count = swift_stdlib_readLine_stdin ( & utf8Start )
32
+ defer {
33
+ _swift_stdlib_free ( utf8Start )
34
34
}
35
- _internalInvariant ( readBytes >= 0 ,
36
- " unexpected return value from swift_stdlib_readLine_stdin " )
37
- if readBytes == 0 {
38
- return " "
35
+ guard utf8Count > 0 else {
36
+ return nil
39
37
}
40
-
41
- let linePtr = linePtrVar!
42
- if strippingNewline {
43
- // FIXME: Unicode conformance. To fix this, we need to reimplement the
44
- // code we call above to get a line, since it will only stop on LF.
45
- //
46
- // <rdar://problem/20013999> Recognize Unicode newlines in readLine()
47
- //
48
- // Recognize only LF and CR+LF combinations for now.
49
- let cr = UInt8 ( ascii: " \r " )
50
- let lf = UInt8 ( ascii: " \n " )
51
- if readBytes == 1 && linePtr [ 0 ] == lf {
52
- return " "
53
- }
54
- if readBytes >= 2 {
55
- switch ( linePtr [ readBytes - 2 ] , linePtr [ readBytes - 1 ] ) {
56
- case ( cr, lf) :
57
- readBytes -= 2
58
- break
59
- case ( _, lf) :
60
- readBytes -= 1
61
- break
62
- default :
63
- ( )
64
- }
65
- }
38
+ let utf8Buffer = UnsafeBufferPointer ( start: utf8Start, count: utf8Count)
39
+ var result = String . _fromUTF8Repairing ( utf8Buffer) . result
40
+ if strippingNewline, result. last == " \n " || result. last == " \r \n " {
41
+ _ = result. removeLast ( )
66
42
}
67
- let result = String . _fromUTF8Repairing (
68
- UnsafeBufferPointer ( start: linePtr, count: readBytes) ) . 0
69
- _swift_stdlib_free ( linePtr)
70
43
return result
71
44
}
0 commit comments