Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
File.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Compiler.h"
5#ifndef SC_EXPORT_LIBRARY_FILE
6#define SC_EXPORT_LIBRARY_FILE 0
7#endif
8#define SC_FILE_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_FILE)
9
10#include "../Foundation/Internal/IGrowableBuffer.h"
11#include "../Foundation/PrimitiveTypes.h"
12#include "../Foundation/Result.h"
13#include "../Foundation/Span.h"
14#include "../Foundation/StringPath.h"
15#include "../Foundation/StringSpan.h"
16#include "../Foundation/UniqueHandle.h"
17
20
21namespace SC
22{
23namespace detail
24{
25#if SC_PLATFORM_WINDOWS
26struct SC_FILE_EXPORT FileDescriptorDefinition
27{
28 using Handle = void*; // HANDLE
29 static Result releaseHandle(Handle& handle);
30#ifdef __clang__
31 static constexpr void* Invalid = __builtin_constant_p(-1) ? (void*)-1 : (void*)-1; // INVALID_HANDLE_VALUE
32#else
33 static constexpr void* Invalid = (void*)-1; // INVALID_HANDLE_VALUE
34#endif
35};
36
37#else
39
41struct SC_FILE_EXPORT FileDescriptorDefinition
42{
43 using Handle = int; // fd
44 static Result releaseHandle(Handle& handle);
45
46 static constexpr Handle Invalid = -1; // invalid fd
47};
49#endif
50} // namespace detail
51
54
57{
58 Unknown,
59 File,
60 Directory,
61 SymbolicLink,
62 Other,
63};
64
96
98struct SC_FILE_EXPORT FileOpen
99{
110
111 FileOpen(Mode mode = Read) : mode(mode) {}
112
114 bool inheritable = false;
115 bool blocking = true;
116 bool sync = false;
117 bool exclusive = false;
118
119#if !SC_PLATFORM_WINDOWS
120 int toPosixFlags() const;
121 int toPosixAccess() const;
122#endif
123};
125
127struct SC_FILE_EXPORT FileDescriptor : public UniqueHandle<detail::FileDescriptorDefinition>
128{
129 using UniqueHandle::UniqueHandle;
130
133
137
141
145
149
155
161 Result read(Span<char> data, Span<char>& actuallyRead, uint64_t offset);
162
168 Result read(Span<uint8_t> data, Span<uint8_t>& actuallyRead, uint64_t offset);
169
174 Result read(Span<char> data, Span<char>& actuallyRead);
175
181
187
193 template <typename T>
194 Result readUntilEOF(T& destination)
195 {
196 return readUntilEOF(GrowableBuffer<T>{destination});
197 }
198
203 Result readUntilEOF(IGrowableBuffer&& buffer);
204
209
215
221
226
231
239
244 Result seek(SeekMode seekMode, int64_t offset);
245
249 Result currentPosition(size_t& position) const;
250
254 Result sizeInBytes(size_t& sizeInBytes) const;
255
260
265
271
275
279
284
285 private:
286 friend struct File;
287 friend struct PipeDescriptor;
288 struct Internal;
289};
290
291struct SC_FILE_EXPORT PipeOptions
292{
293 bool readInheritable = false;
294 bool writeInheritable = false;
295 bool blocking = true;
296};
297
312
313struct SC_FILE_EXPORT NamedPipeNameOptions
314{
315 StringSpan posixDirectory = "/tmp";
316};
317
319struct SC_FILE_EXPORT NamedPipeName
320{
326 static Result build(StringSpan logicalName, StringPath& outName, NamedPipeNameOptions options = {});
327};
328
329struct SC_FILE_EXPORT NamedPipeServerOptions
330{
331 PipeOptions connectionOptions = {};
332 uint32_t maxPendingConnections = 16;
333
334 struct Posix
335 {
336 bool removeEndpointOnClose = true;
337 bool removeEndpointBeforeCreate = false;
338 } posix;
339};
340
341struct SC_FILE_EXPORT NamedPipeClientOptions
342{
343 PipeOptions connectionOptions = {};
344 struct Windows
345 {
346 uint32_t connectTimeoutMilliseconds = 0xffffffff;
347 } windows;
348};
349
354struct SC_FILE_EXPORT NamedPipeServer
355{
366 Result accept(PipeDescriptor& outConnection);
371
372 private:
374 StringPath name;
375#if SC_PLATFORM_WINDOWS
376 FileDescriptor pendingConnection;
377 bool firstInstance = true;
378#else
379 FileDescriptor listeningSocket;
380#endif
381 bool created = false;
382};
383
385struct SC_FILE_EXPORT NamedPipeClient
386{
394 static Result connect(StringSpan name, PipeDescriptor& outConnection, NamedPipeClientOptions options = {});
395};
397} // namespace SC
@ Read
Check if path is readable.
FileDescriptorEntryType
A structure to describe metadata associated with an open descriptor.
Definition File.h:57
unsigned char uint8_t
Platform independent (1) byte unsigned int.
Definition PrimitiveTypes.h:27
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition PrimitiveTypes.h:33
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:29
long long int64_t
Platform independent (8) bytes signed int.
Definition PrimitiveTypes.h:41
A structure to describe file stats queried through a file descriptor.
Definition File.h:67
uint32_t reparseTag
Windows reparse tag.
Definition File.h:91
uint32_t uid
POSIX st_uid.
Definition File.h:79
uint32_t mode
POSIX st_mode.
Definition File.h:78
uint64_t blockSize
POSIX st_blksize.
Definition File.h:85
uint64_t fileIndex
Windows file index.
Definition File.h:93
uint32_t attributes
Windows file attributes.
Definition File.h:90
FileDescriptorEntryType entryType
Type of entry associated with descriptor.
Definition File.h:68
TimeMs accessedTime
Time when file was last accessed when available.
Definition File.h:73
size_t hardLinkCount
Number of hard links to the entry.
Definition File.h:71
uint64_t device
POSIX st_dev.
Definition File.h:82
uint64_t specialDevice
POSIX st_rdev.
Definition File.h:83
TimeMs modifiedTime
Time when file was last modified.
Definition File.h:74
uint64_t blocks
POSIX st_blocks.
Definition File.h:84
size_t fileSize
Size of the file in bytes.
Definition File.h:70
uint32_t volumeSerialNumber
Windows volume serial number.
Definition File.h:92
uint32_t gid
POSIX st_gid.
Definition File.h:80
TimeMs creationTime
Time when file was created when available.
Definition File.h:72
uint64_t inode
POSIX st_ino.
Definition File.h:81
[UniqueHandleDeclaration2Snippet]
Definition File.h:128
SeekMode
How the offset to FileDescriptor::seek is defined.
Definition File.h:234
@ SeekCurrent
Offset to FileDescriptor::seek is to be applied from current descriptor position.
Definition File.h:237
@ SeekEnd
Offset to FileDescriptor::seek is to be applied (backwards) from end of descriptor.
Definition File.h:236
@ SeekStart
Offset to FileDescriptor::seek is to be applied from start of descriptor.
Definition File.h:235
Result syncData()
Flush file data to stable storage.
Result read(Span< uint8_t > data, Span< uint8_t > &actuallyRead)
Reads bytes from current position (FileDescriptor::seek) into user supplied Span.
Result openForWriteToDevNull()
... [UniqueHandleDeclaration2Snippet]
Result write(Span< const uint8_t > data, uint64_t offset)
Writes bytes at offset from start of the file descriptor.
Result openStdErrDuplicate()
Opens a duplicated file descriptor handle for reading from stderr.
Result chmod(uint32_t mode)
Change file permission bits for the currently open descriptor.
Result readUntilEOF(T &destination)
Reads into a given dynamic buffer until End of File (EOF) is signaled.
Definition File.h:194
Result readUntilEOF(IGrowableBuffer &&buffer)
Reads into a given dynamic buffer until End of File (EOF) is signaled.
Result seek(SeekMode seekMode, int64_t offset)
Changes the current position in the file descriptor, if seekable.
Result stat(FileDescriptorStat &fileStat) const
Obtains richer metadata associated with the currently open descriptor.
Result read(Span< char > data, Span< char > &actuallyRead)
Reads bytes from current position (FileDescriptor::seek) into user supplied Span.
Result currentPosition(size_t &position) const
Gets current descriptor position (if seekable)
Result write(Span< const uint8_t > data)
Writes bytes from current position (FileDescriptor::seek) of the file descriptor.
Result write(Span< const char > data, uint64_t offset)
Writes bytes at offset from start of the file descriptor.
Result sizeInBytes(size_t &sizeInBytes) const
Gets total file size in bytes (if seekable)
Result truncate(uint64_t sizeInBytes)
Resize the underlying file to the specified size in bytes.
Result openStdOutDuplicate()
Opens a duplicated file descriptor handle for reading from stdout.
Result read(Span< char > data, Span< char > &actuallyRead, uint64_t offset)
Reads bytes at offset into user supplied span.
Result readUntilFullOrEOF(Span< char > data, Span< char > &actuallyRead)
Reads bytes from current position (FileDescriptor::seek) into Span, until full or EOF is reached.
Result chown(uint32_t uid, uint32_t gid)
Change owner and group for the currently open descriptor.
Result sync()
Flush file data and metadata to stable storage.
Result openStdInDuplicate()
Opens a duplicated file descriptor handle for reading from stdin.
Result open(StringSpan path, FileOpen mode)
Opens a file descriptor handle from a file system path.
Result read(Span< uint8_t > data, Span< uint8_t > &actuallyRead, uint64_t offset)
Reads bytes at offset into user supplied span.
Result writeString(StringSpan data)
Writes a string to the file descriptor.
Result write(Span< const char > data)
Writes bytes from current position (FileDescriptor::seek) of the file descriptor.
Options used to open a file descriptor.
Definition File.h:99
Mode
Indicates the mode in which the file should be opened (read, write, append, etc.)
Definition File.h:102
@ Append
a Open for appending. The file is created if it does not exist.
Definition File.h:105
@ WriteRead
w+ Open for reading and writing. The file is created (if it does not exist) or truncated.
Definition File.h:108
@ ReadWrite
r+ Open for reading and writing. An error occurs if the file does not exist.
Definition File.h:104
@ Write
w Open for writing. The file is created (if it does not exist) or truncated (if it exists).
Definition File.h:107
@ AppendRead
a+ Open for reading and appending. The file is created if it does not exist.
Definition File.h:106
Mode mode
Open mode (read, write, append, etc.). See FileOpen::Mode for more details.
Definition File.h:113
Definition File.h:342
Named pipe client endpoint creator.
Definition File.h:386
static Result connect(StringSpan name, PipeDescriptor &outConnection, NamedPipeClientOptions options={})
Connects to an existing named pipe server endpoint.
Definition File.h:314
Utility for building platform-native named pipe endpoint names from logical names.
Definition File.h:320
static Result build(StringSpan logicalName, StringPath &outName, NamedPipeNameOptions options={})
Builds a platform-native named pipe endpoint path.
Definition File.h:330
Named pipe server endpoint.
Definition File.h:355
Result close()
Closes the listening endpoint.
Result create(StringSpan name, NamedPipeServerOptions options={})
Creates a named pipe server endpoint.
Result accept(PipeDescriptor &outConnection)
Accept one client connection and return it as a connected PipeDescriptor.
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:300
Result createPipe(PipeOptions options={})
Creates a Pipe.
FileDescriptor writePipe
The write side of the pipe.
Definition File.h:302
Result close()
Closes the pipe.
FileDescriptor readPipe
The read side of the pipe.
Definition File.h:301
Definition File.h:292
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
Pre-sized char array holding enough space to represent a file system path.
Definition StringPath.h:42
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37
A vocabulary type representing a time interval in milliseconds since epoch.
Definition PrimitiveTypes.h:50
Move only handle that has a special tag value flagging its invalid state.
Definition UniqueHandle.h:27