From 9bda607649101e3364b4d4b53ed8b684c6d3641e Mon Sep 17 00:00:00 2001 From: Shwoomple <> Date: Sat, 12 Nov 2022 10:59:08 +0530 Subject: [PATCH] lib/file: Implement cut function. --- src/lib/file.cpp | 26 ++++++++++++++++++++++++++ src/test/file.cpp | 14 ++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/lib/file.cpp b/src/lib/file.cpp index b5ca0c5..bfdd245 100644 --- a/src/lib/file.cpp +++ b/src/lib/file.cpp @@ -263,6 +263,32 @@ ErrorOr File::cutByte(){ return failure ? ErrorOr(true, ErrorCodes::UNKNOWN) : ErrorOr(byte); } +ErrorOr> File::cut(uint64_t length){ + bool failure = false; + std::vector bytes; + + try{ + uint8_t* buffer = new uint8_t[this->size.value]; + std::vector readData; + + this->fileStream.read(reinterpret_cast(buffer), this->size.value); + readData = std::vector(buffer, buffer+this->size.value); + + bytes = std::vector(readData.begin() + this->cursorPosition, readData.begin() + (this->cursorPosition + length)); + readData.erase(readData.begin() + this->cursorPosition, readData.begin() + (this->cursorPosition + length)); + + std::filesystem::resize_file(this->path, readData.size()); + this->fileStream.seekg(0); + this->write(readData); + this->cursorPosition += length; + delete[] buffer; + }catch(std::exception& e){ + failure = true; + } + + return failure ? ErrorOr>(true, ErrorCodes::UNKNOWN) :ErrorOr>(bytes); +} + ErrorOr File::open(std::string path, char mode, uint64_t startPosition){ if (!std::filesystem::exists(path) && (mode == 'r' || mode == 'm')) { return ErrorOr(true, ErrorCodes::FILE_NOT_FOUND, nullptr); diff --git a/src/test/file.cpp b/src/test/file.cpp index 29613ef..eddc358 100644 --- a/src/test/file.cpp +++ b/src/test/file.cpp @@ -180,4 +180,18 @@ int main(){ ASSERT(cutByte.value == '.'); ASSERT(cutByteString == "Hallo, Hi THE CAKE IS A LIE, Ich bin Shwoomple"); std::cout << "Passed cut byte test." << std::endl; + + modifyFile->open(); + modifyFile->cursorPosition = 9; + ErrorOr> cutBytes = modifyFile->cut(18); + modifyFile->close(); + + readFile->open(); + readFile->cursorPosition = 0; + tiny_utf8::string cutBytesString = readFile->readString(readFile->size.value).value; + readFile->close(); + + ASSERT(cutBytes.value == std::vector({' ', 'T', 'H', 'E', ' ', 'C', 'A', 'K', 'E', ' ', 'I', 'S', ' ','A', ' ', 'L', 'I', 'E'})) + ASSERT(cutBytesString == "Hallo, Hi, Ich bin Shwoomple"); + std::cout << "Passed cut test." << std::endl; }