lib/file: Implement modify functions

Soda
Shwoomple 2022-10-20 15:12:15 +05:30
parent c825c73afd
commit 8dea1f2d31
2 changed files with 73 additions and 0 deletions

View File

@ -186,6 +186,53 @@ ErrorOrVoid File::insertByte(uint8_t byte){
readData.insert(readData.begin()+this->cursorPosition, byte); readData.insert(readData.begin()+this->cursorPosition, byte);
this->fileStream.seekg(0); this->fileStream.seekg(0);
this->write(readData); this->write(readData);
this->cursorPosition++;
}catch(std::exception& e){
failure = true;
}
return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid();
}
ErrorOrVoid File::insert(std::vector<uint8_t> data){
bool failure = false;
try{
uint8_t* buffer = new uint8_t[this->size.value];
std::vector<uint8_t> readData;
this->fileStream.read(reinterpret_cast<char*>(buffer), this->size.value);
readData = std::vector<uint8_t>(buffer, buffer+this->size.value);
readData.insert(readData.begin()+this->cursorPosition, data.begin(), data.end());
this->fileStream.seekg(0);
this->write(readData);
this->cursorPosition += data.size();
}catch(std::exception& e){
failure = true;
}
return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid();
}
ErrorOrVoid File::insertString(tiny_utf8::string string){
bool failure = false;
try{
uint8_t* buffer = new uint8_t[this->size.value];
tiny_utf8::string readData;
this->fileStream.read(reinterpret_cast<char*>(buffer), this->size.value);
readData = tiny_utf8::string((char *) buffer);
readData.insert(readData.begin()+this->cursorPosition, string);
this->fileStream.seekg(0);
//TODO: fix hack. tinyutf8 appends "_utf-8" when readData is assigned: tiny_utf8::string((char *) buffer);
this->writeString(readData.substr(0, readData.find("_utf-8")));
this->cursorPosition += string.size();
}catch(std::exception& e){ }catch(std::exception& e){
failure = true; failure = true;

View File

@ -138,4 +138,30 @@ int main(){
ASSERT(modifyByteString == "Hallo,, Ich bin Shwoomple."); ASSERT(modifyByteString == "Hallo,, Ich bin Shwoomple.");
std::cout << "Passed modify byte test" << std::endl; std::cout << "Passed modify byte test" << std::endl;
modifyFile->open();
modifyFile->cursorPosition = 6;
modifyFile->insert(std::vector<uint8_t>({' ', 'H', 'i'}));
modifyFile->close();
readFile->open();
readFile->cursorPosition = 0;
tiny_utf8::string modifyBytesString = readFile->readString(readFile->size.value).value;
readFile->close();
ASSERT(modifyBytesString == "Hallo, Hi, Ich bin Shwoomple.");
std::cout << "Passed modify test" << std::endl;
modifyFile->open();
modifyFile->cursorPosition = 9;
modifyFile->insertString(" THE CAKE IS A LIE");
modifyFile->close();
readFile->open();
readFile->cursorPosition = 0;
tiny_utf8::string modifyString = readFile->readString(readFile->size.value).value;
readFile->close();
ASSERT(modifyString == "Hallo, Hi THE CAKE IS A LIE, Ich bin Shwoomple.");
std::cout << "Passed modify string test" << std::endl;
} }