Skip to content

Commit e7be4e2

Browse files
committed
add posix time formatting
1 parent 2c588fd commit e7be4e2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Sources/POSIX/ctime.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
This source file is part of the Swift.org open source project
3+
4+
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
5+
Licensed under Apache License v2.0 with Runtime Library Exception
6+
7+
See http://swift.org/LICENSE.txt for license information
8+
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
9+
*/
10+
11+
import func libc.time
12+
import func libc.ctime
13+
import typealias libc.time_t
14+
15+
public func ctime() throws -> String {
16+
var time = 0
17+
libc.time(&time)
18+
let result = libc.ctime(&time)
19+
20+
return String(cString: result)
21+
}

Sources/POSIX/gmtime.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
This source file is part of the Swift.org open source project
3+
4+
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
5+
Licensed under Apache License v2.0 with Runtime Library Exception
6+
7+
See http://swift.org/LICENSE.txt for license information
8+
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
9+
*/
10+
11+
import typealias libc.time_t
12+
import func libc.strftime
13+
import func libc.gmtime
14+
import func libc.time
15+
16+
public enum StringError: ErrorProtocol {
17+
case NotEnoughSpace
18+
}
19+
20+
extension StringError: CustomStringConvertible {
21+
public var description: String {
22+
switch self {
23+
case .NotEnoughSpace:
24+
return "gmtime error: not enough space, increase resultSize."
25+
}
26+
}
27+
}
28+
29+
public func gmtime(format: String, resultSize: Int = 200) throws -> String {
30+
var time = 0
31+
libc.time(&time)
32+
33+
let result = UnsafeMutablePointer<Int8>(allocatingCapacity: resultSize)
34+
defer {
35+
result.deallocateCapacity(resultSize)
36+
}
37+
38+
let gmTime = gmtime(&time)
39+
guard libc.strftime(result, resultSize, format, gmTime) != 0 else {
40+
throw StringError.NotEnoughSpace
41+
}
42+
43+
return String(cString: result)
44+
}

0 commit comments

Comments
 (0)