Scoop API

scoop:scoop.platform:0.1.0

src/fs/file.scoop

Selected production source · src/fs/file.scoop

1package scoop.platform.fs
3import scoop.platform.io.*
4import scoop.platform.native.fileOpenFlags
5import scoop.platform.native.decodeFileMetadata
6import scoop.platform.memory.NativeByteBuffer
7import scoop.platform.system.OsString
9/**
10 * Explicit file access and creation flags. POSIX permissions are subject to umask; Windows uses the default ACL;
11 * incompatible options are rejected.
12 */
13public struct OpenOptions(
14 val read: Boolean = true,
15 val write: Boolean = false,
16 val append: Boolean = false,
17 val create: Boolean = false,
18 val createNew: Boolean = false,
19 val truncate: Boolean = false,
20 val mode: Int = 0x1b6
23/**
24 * An owned native file handle with byte I/O, positioning, metadata, and explicit durability
25 * operations. Close it after use.
26 */
27public class File private constructor(
28 private val context: OsString?
29): ByteSource, ByteSink, Closeable {
30 private var handle: NativeFileHandle = NativeFileHandle(ULong.MAX_VALUE)
31 private val active: AtomicLong = AtomicLong(0L)
32 /**
33 * Whether this owned resource has been closed.
34 */
35 public val isClosed: Boolean get() = handle.value == ULong.MAX_VALUE
36 /**
37 * Queries the current file offset in bytes.
38 */
39 public fun position(): Long = seekNative(0L, true)
40 /**
41 * Queries the current file length in bytes.
42 */
43 public fun size(): Long = metadata().size
45 /** Acquires a whole-file lock, waiting for conflicting owners. */
46 public fun lock(shared: Boolean = false) {
47 lockNative(
48 if (shared)
49 1
50 else
51 2
52 )
53 }
55 /** Attempts a file lock; only contention returns false. */
56 public fun tryLock(shared: Boolean = false): Boolean =
57 lockNative(
58 if (shared)
59 5
60 else
61 6
62 ) ==
63 0L
65 /** Releases this owner's file lock. */
66 public fun unlock() {
67 lockNative(0)
68 }
70 private fun lockNative(operation: Int): Long =
71 withHandle {
72 fd -> @Unsafe
73 {
74 return@withHandle nativeFileLock(fd, operation).checked("file lock", context)
75 }
76 }
78 /**
79 * Opens owned file handles with explicit access and creation policy.
80 */
81 public companion object {
82 // Pipe/spawn callers allocate all managed owners before acquiring native handles.
83 internal fun newOwner(): File = File(None)
85 /**
86 * Opens the path using the supplied options; failures retain platform error details and
87 * path context.
88 */
89 public fun open(path: Path, options: OpenOptions = OpenOptions()): File {
90 val flags = fileOpenFlags(options)
91 val file = File(Some(path.toOsString()))
92 @Unsafe
93 {
94 val opened =
95 path.withPlatformPath {
96 pointer -> @Unsafe
97 {
98 return@withPlatformPath nativeFileOpen(pointer, flags, options.mode)
99 }
100 }
101 file.handle = opened.checked("open", file.context)
102 }
103 return file
104 }
106 internal fun duplicateHandle(fd: NativeFileHandle, context: OsString? = None): File {
107 val file = File(context)
108 @Unsafe
109 {
110 file.handle = nativeFileDuplicate(fd).checked("duplicate", context)
111 }
112 return file
113 }
114 }
116 internal fun adoptHandle(owned: NativeFileHandle) {
117 handle = owned
118 }
120 internal fun <R> withHandle(block: (NativeFileHandle) -> R): R {
121 requireOpen()
122 active.fetchAdd(1L, MemoryOrder.Relaxed)
123 try {
124 return block(handle)
125 }
126 finally {
127 active.fetchSub(1L, MemoryOrder.Relaxed)
128 }
129 }
131 private fun requireOpen() {
132 if (handle.value == ULong.MAX_VALUE)
133 throw IllegalStateException(Some("file is closed"))
134 }
136 /**
137 * Duplicates the native descriptor into a separately owned File. Descriptor duplication shares
138 * the underlying open-file offset.
139 */
140 public fun duplicate(): File = withHandle { fd -> File.duplicateHandle(fd, context) }
142 /**
143 * Reads into the selected writable region, returning actual bytes and permitting short reads.
144 * Zero for a positive request denotes EOF.
145 */
146 public override fun readInto(buffer: NativeByteBuffer, count: Long): Long =
147 withHandle { fd -> readFileHandle(fd, buffer, count, context) }
149 /**
150 * Consumes the selected readable region, returning the actual accepted byte count and
151 * permitting short writes.
152 */
153 public override fun writeFrom(buffer: NativeByteBuffer, count: Long): Long =
154 withHandle { fd -> writeFileHandle(fd, buffer, count, context) }
156 /**
157 * Reads into the selected writable region, returning actual bytes and permitting short reads.
158 * Zero for a positive request denotes EOF.
159 */
160 public fun readInto(
161 array: MutableArray<Byte>,
162 offset: Long = 0L,
163 count: Long = array.size - offset
164 ): Long {
165 return withHandle {
166 fd ->
167 requireArrayTransfer(array.size, offset, count)
168 if (count == 0L)
169 return@withHandle 0L
170 @Unsafe
171 {
172 return@withHandle array.withDataPointer {
173 pointer,
174 _ -> @Unsafe
175 {
176 return@withDataPointer nativeFileRead(fd, pointer + offset, count).checked(
177 "read",
178 context
179 )
180 }
181 }
182 }
183 }
184 }
186 /**
187 * Consumes the selected readable region, returning the actual accepted byte count and
188 * permitting short writes.
189 */
190 public fun writeFrom(
191 array: List<Byte>,
192 offset: Long = 0L,
193 count: Long = array.size - offset
194 ): Long {
195 return withHandle {
196 fd ->
197 requireArrayTransfer(array.size, offset, count)
198 if (count == 0L)
199 return@withHandle 0L
200 val snapshot = Array<Byte>(count) { index -> array[offset + index] }
201 @Unsafe
202 {
203 return@withHandle snapshot.withDataPointer {
204 pointer,
205 _ -> @Unsafe
206 {
207 return@withDataPointer writeArray(fd, pointer, count)
208 }
209 }
210 }
211 }
212 }
214 @Unsafe
215 private fun writeArray(fd: NativeFileHandle, pointer: Ptr<Byte>, count: Long): Long {
216 val written = nativeFileWrite(fd, pointer, count).checked("write", context)
217 if (written == 0L)
218 throw WriteZeroException()
219 return written
220 }
222 /**
223 * Sets the file offset to a nonnegative absolute byte position.
224 */
225 public fun seek(position: Long) {
226 requireOpen()
227 if (position < 0L)
228 throw IllegalArgumentException(Some("negative file position"))
229 seekNative(position, false)
230 }
232 private fun seekNative(offset: Long, current: Boolean): Long =
233 withHandle {
234 fd -> @Unsafe
235 {
236 return@withHandle nativeFileSeek(fd, offset, current).checked("seek", context)
237 }
238 }
240 /**
241 * Changes file length using a nonnegative byte size; requires suitable write access.
242 */
243 public fun truncate(size: Long) {
244 withHandle {
245 fd ->
246 if (size < 0L)
247 throw IllegalArgumentException(Some("negative file size"))
248 @Unsafe
249 {
250 nativeFileTruncate(fd, size).checked("truncate", context)
251 }
252 }
253 }
255 /**
256 * Requests persistence of data and metadata required to retrieve the data.
257 */
258 public fun syncData() {
259 sync(true)
260 }
261 /**
262 * Requests persistence of data and full file metadata.
263 */
264 public fun syncAll() {
265 sync(false)
266 }
267 private fun sync(dataOnly: Boolean) {
268 withHandle {
269 fd -> @Unsafe
270 {
271 nativeFileSync(fd, dataOnly).checked("sync", context)
272 }
273 }
274 }
276 /**
277 * Returns metadata for this open descriptor.
278 */
279 public fun metadata(): FileMetadata =
280 withHandle {
281 fd -> @Unsafe
282 {
283 val result = nativeFileMetadata(fd)
284 return@withHandle decodeFileMetadata(result.data, result.error, context)
285 }
286 }
288 /**
289 * Checks that the descriptor is open. File writes are unbuffered here; use syncData or syncAll
290 * for durability.
291 */
292 public override fun flush() {
293 requireOpen()
294 }
296 /**
297 * Closes the owned native handle; subsequent I/O through this owner is invalid.
298 */
299 public override fun close() {
300 if (handle.value == ULong.MAX_VALUE)
301 return
302 if (active.load(MemoryOrder.Relaxed) != 0L)
303 throw IllegalStateException(Some("file operation is active"))
304 val owned = handle
305 handle = NativeFileHandle(ULong.MAX_VALUE)
306 @Unsafe
307 {
308 nativeFileClose(owned).checked("close", context)
309 }
310 }
312 release {
313 if (handle.value != ULong.MAX_VALUE) {
314 @Unsafe
315 {
316 nativeFileClose(handle)
317 }
318 }
319 }
322@Extern(name = "scoop_platform_handle_open")
323private fun nativeFileOpen(path: Ptr<Byte>, flags: Int, mode: Int): NativeFileOpened
325@Extern(name = "scoop_platform_handle_lock")
326private fun nativeFileLock(handle: NativeFileHandle, operation: Int): NativeFileResult
328@Extern(name = "scoop_platform_handle_seek")
329private fun nativeFileSeek(
330 handle: NativeFileHandle,
331 offset: Long,
332 current: Boolean
333): NativeFileResult
335@Extern(name = "scoop_platform_handle_truncate")
336private fun nativeFileTruncate(handle: NativeFileHandle, size: Long): NativeFileResult
338@Extern(name = "scoop_platform_handle_sync")
339private fun nativeFileSync(handle: NativeFileHandle, dataOnly: Boolean): NativeFileResult
341@Extern(name = "scoop_platform_handle_same")
342internal fun nativeSameFile(first: NativeFileHandle, second: NativeFileHandle): NativeFileResult