Skip to content

Commit

Permalink
Merge pull request #148 from finagolfin/droid
Browse files Browse the repository at this point in the history
Android: update pread/pwrite for nullability annotations in NDK 26
  • Loading branch information
glessard authored Mar 20, 2024
2 parents 403776d + 5ca37e7 commit dae787c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Sources/System/Internals/Syscalls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,15 @@ internal func system_pread(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pread has a non-nullable `buf` pointer
pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset)
}
#else
return pread(fd, buf, nbyte, offset)
#endif
}

// lseek
Expand Down Expand Up @@ -101,7 +109,15 @@ internal func system_pwrite(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pwrite has a non-nullable `buf` pointer
pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset)
}
#else
return pwrite(fd, buf, nbyte, offset)
#endif
}

internal func system_dup(_ fd: Int32) -> Int32 {
Expand Down
24 changes: 24 additions & 0 deletions Tests/SystemTests/FileOperationsTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,30 @@ final class FileOperationsTest: XCTestCase {
for test in syscallTestCases { test.runAllTests() }
}

func testWriteFromEmptyBuffer() throws {
let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
let written1 = try fd.write(toAbsoluteOffset: 0, .init(start: nil, count: 0))
XCTAssertEqual(written1, 0)

let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeRawBufferPointer(start: pointer, count: 0)
let written2 = try fd.write(toAbsoluteOffset: 0, empty)
XCTAssertEqual(written2, 0)
}

func testReadToEmptyBuffer() throws {
let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly)
let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0))
XCTAssertEqual(read1, 0)

let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0)
let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty)
XCTAssertEqual(read2, 0)
}

func testHelpers() {
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
}
Expand Down

0 comments on commit dae787c

Please sign in to comment.