Here is a simple and very fast format.
It's written in C++, it uses a full structure serialization (a memory imprint) with pointer fixups. This technique is used by many formats.
It's a super simple barebone format, where you can add many more features, boundaries are limitless.
Code: Select all
/*
Some sample code made by Lukas Cone.
I hereby place this code under the Public Domain.
TL,DR: Use this however you want
*/
#include <fstream>
#include <vector>
#include <cstring>
struct Header
{
int signature = 0x12345678;
short version = 1;
short numSentences = 0;
char **sentences = nullptr;
};
Header *LoadFormat(const char *filePath)
{
std::ifstream str(filePath, std::ios_base::binary | std::ios_base::in | std::ios_base::ate);
if (str.fail())
return nullptr;
const size_t fileSize = str.tellg();
char *buffer = static_cast<char*>(malloc(fileSize));
str.seekg(0);
//add testing for a signature
str.read(buffer, fileSize);
str.close();
Header *hdr = reinterpret_cast<Header *>(buffer);
hdr->sentences = reinterpret_cast<char**>(buffer + reinterpret_cast<intptr_t>(hdr->sentences));
for (int s = 0; s < hdr->numSentences; s++)
hdr->sentences[s] = buffer + reinterpret_cast<intptr_t>(hdr->sentences[s]);
return hdr;
}
void SaveFormat(const char *filePath, const Header &hdr)
{
std::ofstream str(filePath, std::ios_base::out | std::ios_base::binary);
Header outHdr = hdr;
outHdr.sentences = reinterpret_cast<char**>(sizeof(Header));
str.write(reinterpret_cast<const char*>(&outHdr), sizeof(Header));
const size_t savepos = str.tellp();
std::vector<size_t> strLens;
strLens.reserve(hdr.numSentences);
str.seekp(sizeof(void*) * hdr.numSentences, std::ios_base::cur);
for (int s = 0; s < hdr.numSentences; s++)
{
const size_t cStrSize = strlen(hdr.sentences[s]) + 1;
str.write(hdr.sentences[s], cStrSize);
strLens.push_back(cStrSize);
}
str.seekp(savepos);
size_t lastOffset = savepos + sizeof(void*) * hdr.numSentences;
for (auto &a : strLens)
{
str.write(reinterpret_cast<const char*>(&lastOffset), sizeof(void*));
lastOffset += a;
}
str.close();
}
static char s1[] = "Thank you solve this";
static char s2[] = "How to solve this bro?";
static char s3[] = "I'm just wondering";
static char *sentences[] = {s1, s2, s3};
int main()
{
Header test;
test.numSentences = 3;
test.sentences = sentences;
SaveFormat("testing.f", test);
Header *testInput = LoadFormat("testing.f");
if (test.numSentences != testInput->numSentences)
return 1;
for (int s = 0; s < 3; s++)
if (strcmp(test.sentences[s], testInput->sentences[s]))
return 2;
return 0;
}