AuroraRuntime/Source/IO/FS/FileStream.NT.cpp
Reece cf70f0d45c [*/+/-] MEGA COMMIT. ~2 weeks compressed.
The intention is to quickly improve and add util apis, enhance functionality given current demands, go back to the build pipeline, finish that, publish runtime tests, and then use what we have to go back to to linux support with a more stable api.

[+] AuMakeSharedArray
[+] Technet ArgvQuote
[+] Grug subsystem (UNIX signal thread async safe ipc + telemetry flusher + log flusher.)
[+] auEndianness -> Endian swap utils
[+] AuGet<N>(...)
[*] AUE_DEFINE conversion for
        ECompresionType, EAnsiColor, EHashType, EStreamError, EHexDump
[+] ConsoleMessage ByteBuffer serialization
[+] CmdLine subsystem for parsing command line arguments and simple switch/flag checks
[*] Split logger from console subsystem
[+] StartupParameters -> A part of a clean up effort under Process
[*] Refactor SysErrors header + get caller hack
[+] Atomic APIs
[+] popcnt
[+] Ring Buffer sink
[+] Added more standard errors
        Catch,
        Submission,
        LockError,
        NoAccess,
        ResourceMissing,
        ResourceLocked,
        MalformedData,
        InSandboxContext,
        ParseError

[+] Added ErrorCategorySet, ErrorCategoryClear, GetStackTrace
[+] IExitSubscriber, ETriggerLevel
[*] Write bias the high performance RWLockImpl read-lock operation operation
[+] ExitHandlerAdd/ExitHandlerRemove (exit subsystem)
[*] Updated API style
        Digests
[+] CpuId::CpuBitCount
[+] GetUserProgramsFolder
[+] GetPackagePath
[*] Split IStreamReader with an inl file
[*] BlobWriter/BlobReader/BlobArbitraryReader can now take shared pointers to bytebuffers. default constructor allocates a new scalable bytebuffer
[+] ICharacterProvider
[+] ICharacterProviderEx
[+] IBufferedCharacterConsumer
[+] ProviderFromSharedString
[+] ProviderFromString
[+] BufferConsumerFromProvider
[*] Parse Subsystem uses character io bufferer
[*] Rewritten NT's high perf semaphore to use userland SRW/ConVars [like mutex, based on generic semaphore]
[+] ByteBuffer::ResetReadPointer
[*] Bug fix bytebuffer base not reset on free and some scaling issues
[+] ProcessMap -> Added kSectionNameStack, kSectionNameFile, kSectionNameHeap for Section
[*] ProcessMap -> Refactor Segment to Section. I was stupid for keeping a type conflict hack API facing
[+] Added 64 *byte* fast RNG seeds
[+] File Advisorys/File Lock Awareness
[+] Added extended IAuroraThread from OS identifier caches for debug purposes
[*] Tweaked how memory is reported on Windows. Better consistency of what values mean across functions.
[*] Broke AuroraUtils/Typedefs out into a separate library
[*] Update build script
[+] Put some more effort into adding detail to the readme before rewriting it, plus, added some media
[*] Improved public API documentation
[*] Bug fix `SetConsoleCtrlHandler`
[+] Locale TimeDateToFileNameISO8601
[+] Console config stdOutShortTime
[*] Begin using internal UTF8/16 decoders when platform support isnt available (instead of stl)
[*] Bug fixes in decoders
[*] Major bug fix, AuMax
[+] RateLimiter
[+] Binary file sink
[+] Log directory sink
[*] Data header usability (more operators)
[+] AuRemoveRange
[+] AuRemove
[+] AuTryRemove
[+] AuTryRemoveRange
[+] auCastUtils
[+] Finish NewLSWin32Source
[+] AuTryFindByTupleN, AuTryRemoveByTupleN
[+] Separated AuRead/Write types, now in auTypeUtils
[+] Added GetPosition/SetPosition to FileWriter
[*] Fix stupid AuMin in place of AuMax in SpawnThread.Unix.Cpp
[*] Refactored Arbitrary readers to SeekingReaders (as in, they could be atomic and/or parallelized, and accept an arbitrary position as a work parameter -> not Seekable, as in, you can simply set the position)
[*] Hack back in the sched deinit
[+] File AIO loop source interop
[+] Begin to prototype a LoopQueue object I had in mind for NT, untested btw
[+] Stub code for networking
[+] Compression BaseStream/IngestableStreamBase
[*] Major: read/write locks now support write-entrant read routines.
[*] Compression subsystem now uses the MemoryView concept
[*] Rewrite the base stream compressions, made them less broken
[*] Update hashing api
[*] WriterTryGoForward and ReaderTryGoForward now revert to the previous relative index instead of panicing
[+] Added new AuByteBuffer apis
    Trim, Pad, WriteFrom, WriteString, [TODO: ReadString]
[+] Added ByteBufferPushReadState
[+] Added ByteBufferPushWriteState
[*] Move from USC-16 to full UTF-16. Win32 can handle full UTF-16.
[*] ELogLevel is now an Aurora enum
[+] Raised arbitrary limit in header to 255, the max filter buffer
[+] Explicit GZip support
[+] Explicit Zip support
[+] Added [some] compressors

et al
2022-02-17 00:11:40 +00:00

283 lines
7.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: FileStream.NT.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "FS.hpp"
#include "FileStream.NT.hpp"
#include "FileAdvisory.NT.hpp"
#if !defined(_AURUNTIME_GENERICFILESTREAM)
namespace Aurora::IO::FS
{
static const AuUInt64 kFileCopyBlock = 0xFFFF; // 64KiB, 1k iterations to max out 64MB/s disk, 2k iteration to make out 128MB/s disk, is this number still way too low? cpu go brr
WinFileStream::~WinFileStream()
{
Close();
}
void WinFileStream::Init(HANDLE handle, const AuString &path)
{
handle_ = handle;
path_ = path;
}
AuUInt64 WinFileStream::GetOffset()
{
LARGE_INTEGER distance {};
LARGE_INTEGER pos {};
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return 0;
}
if (SetFilePointerEx(handle_, distance, &pos, FILE_CURRENT) == INVALID_SET_FILE_POINTER)
{
AuLogWarn("SetFilePointerEx IO Error: 0x{:x}, {}", GetLastError(), path_);
SysPushErrorIO();
return 0;
}
return pos.QuadPart;
}
bool WinFileStream::SetOffset(AuUInt64 offset)
{
LARGE_INTEGER distance {};
LARGE_INTEGER pos {};
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return false;
}
distance.QuadPart = offset;
if (SetFilePointerEx(handle_, distance, &pos, FILE_CURRENT) == INVALID_SET_FILE_POINTER)
{
AuLogWarn("SetFilePointerEx IO Error: 0x{:x}, {}", GetLastError(), path_);
SysPushErrorIO();
return false;
}
return true;
}
AuUInt64 WinFileStream::GetLength()
{
LARGE_INTEGER length;
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return 0;
}
if (!GetFileSizeEx(handle_, &length))
{
SysPushErrorIO();
return 0;
}
return length.QuadPart;
}
bool WinFileStream::Read(const Memory::MemoryViewStreamWrite &parameters)
{
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return {};
}
auto length = parameters.length;
AuUInt64 offset {0};
while (length)
{
DWORD read;
int blockSize = AuMin(kFileCopyBlock, length);
if (!::ReadFile(handle_, reinterpret_cast<char *>(parameters.ptr) + offset, blockSize, &read, NULL))
{
AuLogWarn("ReadFile IO Error: 0x{:x}, {}", GetLastError(), path_);
SysPushErrorIO();
return false;
}
if (read == 0)
{
break;
}
offset += read;
length -= read;
}
if (!offset)
{
return false;
}
parameters.outVariable = offset;
return true;
}
bool WinFileStream::Write(const Memory::MemoryViewStreamRead &parameters)
{
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return 0;
}
auto length = parameters.length;
AuUInt offset {0};
while (length)
{
DWORD written;
int blockSize = AuMin(kFileCopyBlock, length);
if (!::WriteFile(handle_, reinterpret_cast<const char *>(parameters.ptr) + offset, blockSize, &written, NULL))
{
AuLogWarn("WriteFileEx IO Error: 0x{:x}, {}", GetLastError(), path_);
SysPushErrorIO();
return false;
}
if (written != blockSize)
{
SysPushErrorIO();
parameters.outVariable = offset;
return true;
}
offset += written;
length -= written;
}
if (!offset)
{
return false;
}
parameters.outVariable = offset;
return true;
}
void WinFileStream::WriteEoS()
{
if (handle_ == INVALID_HANDLE_VALUE)
{
SysPushErrorUninitialized();
return;
}
SetEndOfFile(handle_);
}
void WinFileStream::Close()
{
AuWin32CloseHandle(handle_);
}
void WinFileStream::Flush()
{
FlushFileBuffers(handle_);
}
AUKN_SYM IFileStream *OpenNew(const AuString &path, EFileOpenMode openMode, EFileAdvisoryLockLevel lock)
{
try
{
auto pathex = NormalizePathRet(path);
if (pathex.empty())
{
return nullptr;
}
auto win32Path = Locale::ConvertFromUTF8(pathex);
if (win32Path.empty())
{
return nullptr;
}
HANDLE fileHandle;
fileHandle = INVALID_HANDLE_VALUE;
switch (openMode)
{
case EFileOpenMode::eRead:
{
fileHandle = CreateFileW(win32Path.c_str(), GENERIC_READ, NtLockAdvisoryToShare(lock), NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
break;
}
case EFileOpenMode::eReadWrite:
case EFileOpenMode::eWrite:
{
CreateDirectories(pathex, true);
fileHandle = CreateFileW(win32Path.c_str(), (openMode == EFileOpenMode::eReadWrite) ? (GENERIC_WRITE | GENERIC_READ) : GENERIC_WRITE, NtLockAdvisoryToShare(lock), NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
break;
}
}
if (fileHandle == INVALID_HANDLE_VALUE)
{
AuLogWarn("Missing file: {}", path);
SysPushErrorIO("Missing file: {}", path);
return nullptr;
}
auto stream = _new WinFileStream();
if (!stream)
{
CloseHandle(fileHandle);
return nullptr;
}
stream->Init(fileHandle, pathex);
return stream;
}
catch (...)
{
return nullptr;
}
}
AUKN_SYM void OpenRelease(IFileStream *that)
{
AuSafeDelete<WinFileStream *>(that);
}
AUKN_SYM IFileStream *OpenReadNew(const AuString &path, EFileAdvisoryLockLevel level)
{
return OpenNew(path, EFileOpenMode::eRead, level);
}
AUKN_SYM void OpenReadRelease(IFileStream * that)
{
AuSafeDelete<WinFileStream *>(that);
}
AUKN_SYM IFileStream *OpenWriteNew(const AuString &path, EFileAdvisoryLockLevel level)
{
return OpenNew(path, EFileOpenMode::eWrite, level);
}
AUKN_SYM void OpenWriteRelease(IFileStream *that)
{
AuSafeDelete<WinFileStream *>(that);
}
}
#endif