From 0e62ad88e8de985b52d3686b69eec0c85e903c87 Mon Sep 17 00:00:00 2001 From: Adam Sharp Date: Sat, 29 May 2021 11:34:00 -0400 Subject: [PATCH] Add non-throwing FileDescriptor.currentOffset helper Provided the file descriptor is still valid, accessing the current offset shouldn't fail. --- Sources/System/FileOperations.swift | 6 ++++++ Tests/SystemTests/FileOperationsTest.swift | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index e2332eee..f493b52e 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -116,6 +116,12 @@ extension FileDescriptor { try _seek(offset: offset, from: whence).get() } + /// Return the current offset for the given file descriptor. + @_alwaysEmitIntoClient + public var currentOffset: Int64 { + try! _seek(offset: 0, from: .current).get() + } + @usableFromInline internal func _seek( offset: Int64, from whence: FileDescriptor.SeekOrigin diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index f39a052a..211f889d 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -90,6 +90,17 @@ final class FileOperationsTest: XCTestCase { // TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter } + func testCurrentOffset() throws { + let fd = try FileDescriptor.open("/tmp/a.txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) + XCTAssertEqual(fd.currentOffset, 0) + + try fd.writeAll("abc".utf8) + XCTAssertEqual(fd.currentOffset, 3) + + try fd.seek(offset: -1, from: .current) + XCTAssertEqual(fd.currentOffset, 2) + } + func testAdHocOpen() { // Ad-hoc test touching a file system. do {