This commit is contained in:
Aria 2025-03-21 22:23:30 +11:00
commit 9c94d113d3
Signed by untrusted user who does not match committer: aria
GPG key ID: 19AB7AA462B8AB3B
10260 changed files with 1237388 additions and 0 deletions

View file

@ -0,0 +1,61 @@
#include "StarPythonic.hpp"
#include "StarString.hpp"
#include "StarFormat.hpp"
using namespace Star;
int main(int argc, char** argv) {
try {
List<int> list = {2, 3, 4, 1, 0};
sortByComputedValue(list, [](int i) { return i; });
coutf("sorted list: %s\n", list);
char something[4] = {'f', 'o', 'o', 0};
coutf("hash1: %s\n", std::hash<char*>()(something));
something[1] = 'u';
coutf("hash2: %s\n", std::hash<char*>()(something));
for (auto const& elem : zip<List>(List<int>{1, 2, 3}))
coutf("tiny zip: %s\n", std::get<0>(elem));
auto zipResult = zip<List>(
List<int>{1, 2, 3},
List<int>{5, 4, 3, 2, 1},
List<int>{3, 2, 2 },
List<int>{0, 0, 0, 0, 4, 8}
);
for (auto const& elem : zipResult)
coutf("zip: %s %s %s %s\n", std::get<0>(elem), std::get<1>(elem), std::get<2>(elem), std::get<3>(elem));
List<int> zla{1, 2, 3};
List<int> zlb{5, 4, 3, 2, 1};
List<int> zlc{3, 2, 2 };
List<int> zld{0, 0, 0, 0, 4, 8};
for (auto const& elem : zipIterator(zla, zlb, zlc, zld)) {
coutf("zip: %s %s %s %s\n", std::get<0>(elem), std::get<1>(elem), std::get<2>(elem), std::get<3>(elem));
std::get<0>(elem) = 0;
}
coutf("mutated zipped list a: %s\n", zla);
for (auto const& elem : range(0, 10, 1))
coutf("range: %s\n", elem);
for (auto const& elem : zip<List>(range(0, 10, 1), range(0, 20, 2), range(0, 100, 5)))
coutf("combined: %s %s %s\n", std::get<0>(elem), std::get<1>(elem), std::get<2>(elem));
coutf("range(0, 10, 3)[5]: %s\n", range(0, 10, 3)[5]);
StringList slist = {"foo", "bar", "baz"};
for (auto const& pair : enumerate<List>(slist))
coutf("enumerate output: %s %s\n", pair.first, pair.second);
} catch (std::exception const& e) {
cerrf("exception caught: %s\n", e.what());
return 1;
}
return 0;
}

View file

@ -0,0 +1,64 @@
#include "StarAny.hpp"
#include "StarFormat.hpp"
#include "StarLexicalCast.hpp"
using namespace Star;
struct MyStruct {
MyStruct() {
i = 100;
}
MyStruct(MyStruct const& rhs) {
i = rhs.i;
}
MyStruct(int i) : i(i) {}
~MyStruct() {
}
int i;
};
std::ostream& operator<<(std::ostream& os, MyStruct const& s) {
os << s.i;
return os;
}
struct ToStringer {
template<typename T>
String operator()(T const& op) {
return toString(op);
}
};
int main(int argc, char** argv) {
try {
coutf("Internal any policy for int: %s\n", AnyDetail::getPolicy<int>()->isInternal());
coutf("Internal any policy for int64_t: %s\n", AnyDetail::getPolicy<uint64_t>()->isInternal());
coutf("Internal any policy for shared_ptr<char>: %s\n", AnyDetail::getPolicy<shared_ptr<char>>()->isInternal());
coutf("Internal any policy for shared_ptr<char const>: %s\n", AnyDetail::getPolicy<shared_ptr<char const>>()->isInternal());
coutf("Internal any policy for char*: %s\n", AnyDetail::getPolicy<char*>()->isInternal());
coutf("Internal any policy for char const*: %s\n", AnyDetail::getPolicy<char const*>()->isInternal());
coutf("Internal any policy for MyStruct: %s\n", AnyDetail::getPolicy<MyStruct>()->isInternal());
typedef AnyOf<int, char const*, MyStruct> MyAny;
MyAny a = MyStruct{2};
MyAny b = a;
b = 2;
b = a;
a = "foo";
coutf("Printing any values: %s %s\n", a.capply(ToStringer()), b.capply(ToStringer()));
MyAny c;
c.makeType(3);
coutf("Held type %s, printing after setting to different type via makeType: %s\n", c.getType(), c.apply(ToStringer()));
return 0;
} catch (std::exception const& e) {
coutf("Exception caught: %s\n", e.what());
return 1;
}
}

View file

@ -0,0 +1,69 @@
#include <iostream>
#include "StarBlockStorage.hpp"
#include "StarFile.hpp"
#include "StarFormat.hpp"
using namespace Star;
using namespace std;
static size_t TotalCount = 20;
static size_t FreeCount = 10;
static size_t BlockSize = 128;
static size_t TestRepeatCount = 10;
int main(int argc, char** argv) {
BlockStoragePtr bs = std::make_shared<BlockStorage>();
bs->setIODevice(File::open("./blocktest", File::ReadWrite | File::Truncate));
bs->setBlockSize(BlockSize);
bs->open();
bs->writeToUserHeader(0, "01234567", 8);
size_t next = 0;
List<BlockStorage::BlockIndex> usedBlocks;
bs->reserveBlocks(TotalCount, back_inserter(usedBlocks));
ByteArray writeBlock(BlockSize, 0);
cout << "writing: ";
for (BlockStorage::BlockIndex b : usedBlocks) {
coutf("(%s:%s) ", next, b);
writeBlock.fill((char)next++);
bs->updateBlock(b, writeBlock);
}
cout << endl;
for (size_t repeat = 0; repeat < TestRepeatCount; ++repeat) {
std::random_shuffle(usedBlocks.begin(), usedBlocks.end());
getc(stdin);
List<BlockStorage::BlockIndex> blocksToFree = usedBlocks.slice(0, FreeCount);
usedBlocks.erase(0, FreeCount);
cout << "freeing: " << blocksToFree << endl;
bs->freeBlocks(blocksToFree.begin(), blocksToFree.end());
getc(stdin);
List<BlockStorage::BlockIndex> reserveBlocks;
bs->reserveBlocks(FreeCount, back_inserter(reserveBlocks));
cout << "writing: ";
for (BlockStorage::BlockIndex b : reserveBlocks) {
coutf("(%s:%s) ", next, b);
writeBlock.fill((char)next++);
bs->updateBlock(b, writeBlock);
usedBlocks.append(b);
}
cout << endl;
}
getc(stdin);
cout << "freeing all" << endl;
bs->freeBlocks(usedBlocks.begin(), usedBlocks.end());
getc(stdin);
cout << "shrinking and closing" << endl;
bs->shrink();
bs->close();
}

View file

@ -0,0 +1,28 @@
#include <cstring>
#include "StarCompression.hpp"
#include "StarFormat.hpp"
#include "StarMap.hpp"
using namespace Star;
int main(int argc, char** argv) {
char const* testData =
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab"
"ababababababababababababababababababababababababab";
ByteArray compressedData = compressData(ByteArray(testData, strlen(testData)));
coutf("compressed data size %s\n", compressedData.size());
ByteArray uncompressedData = uncompressData(compressedData);
coutf("uncompressed data size %s\n", uncompressedData.size());
return 0;
}

View file

@ -0,0 +1,24 @@
#include "StarRoot.hpp"
#include "StarCelestialDatabase.hpp"
using namespace Star;
int main(int argc, char** argv) {
try {
auto root = make_shared<Root>("./assets");
auto celestialDatabase = root->celestialDatabase();
if (argc == 2) {
auto system = celestialDatabase->parseSystemCoordinate(argv[1]);
coutf("Given system: %s %s\n", system, system.systemName());
} else {
auto randSystem = celestialDatabase->findRandomSystem();
coutf("Random system: %s %s\n", randSystem, randSystem.systemName());
}
return 0;
} catch(std::exception const& e) {
cerrf("exception caught: %s\n", e.what());
return 1;
}
}

View file

@ -0,0 +1,32 @@
#include "StarImage.hpp"
#include "StarImageProcessing.hpp"
#include "StarFormat.hpp"
#include "StarAssets.hpp"
using namespace Star;
int main(int argc, char** argv) {
if (argc != 4) {
coutf("usage <image> <operationlist> <output>\n");
return 1;
}
try {
ImagePtr image = Image::loadPng(argv[1]);
ImageProcessor processor = ImageProcessor(argv[2]);
for (auto ref : processor.imageReferences())
processor.setImageReference(ref, Image::loadPng(ref.utf8Ptr()));
coutf("processing parameters: %s\n", processor.printOperations());
auto result = processor.process(image);
coutf("done\n");
result->writePng(argv[3]);
return 0;
} catch (std::exception const& e) {
coutf("Exception caught: %s\n", e.what());
return 1;
}
}

View file

@ -0,0 +1,19 @@
#include "StarPoly.hpp"
#include "StarFormat.hpp"
using namespace Star;
int main(int argc, char** argv) {
Line2F line = {Vec2F(-1.87231, -0.557495), Vec2F(-0.20874, -0.455933)};
PolyF poly;
poly.add(Vec2F(-0.375, -1.5));
poly.add(Vec2F(0.375, -1.5));
poly.add(Vec2F(0.375, 0.125));
poly.add(Vec2F(-0.375, 0.125));
if (poly.intersects(line)) {
coutf("Intersects\n");
} else {
coutf("No intersection\n");
}
}

View file

@ -0,0 +1,17 @@
#include "StarLine.hpp"
#include "StarFormat.hpp"
using namespace Star;
int main(int argc, char** argv) {
Line2F a = {Vec2F(-.9, 1), Vec2F(1, -1)};
Line2F b = {Vec2F(-1, 0), Vec2F(1, 0)};
if (a.intersects(b).intersects) {
coutf("pass\n");
} else {
coutf("fail\n");
}
return 0;
}

View file

@ -0,0 +1,16 @@
#include "StarLinq.hpp"
using namespace Star;
int main(int argc, char** argv) {
List<int> src = {1,2,3,4,5,6,7,8};
List<int> dst = Linq::from(src).where([](int a){return a%2 == 1;}) // 1,3,5,7
.select([](int a){return a*2;}) // 2,6,10,14
.where( [](int a){return a>2 && a<12;}) // 6,10
.toStarList();
coutf("%s\n", dst);
return 0;
}

View file

@ -0,0 +1,54 @@
#include <fstream>
#include "StarVariant.hpp"
#include "StarLua.hpp"
#include "StarFormat.hpp"
using namespace Star;
using namespace std;
int main(int argc, char** argv) {
try {
LuaEnginePtr luaRoot = LuaEngine::create();
luaRoot->loadScript("hello",
R"SCRIPT(
function doit()
self.called = self.called + 1
print("Hello, I am " .. callbacks.name() .. " from " .. self.location .. ", I have " .. self.called .. " matchstick.")
end
)SCRIPT");
luaRoot->loadScript("respond",
R"SCRIPT(
function doit()
self.called = self.called + 1
print("Hello " .. callbacks.name() .. " I am from " .. self.location .. ", I have " .. self.called .. " matchstick.")
end
)SCRIPT");
LuaCallbacks callbacks;
auto helloContext = luaRoot->scriptContext("hello");
helloContext->addPersistentTable("self", {{"location", "Sweden"}, {"called", 0}});
auto respondContext = luaRoot->scriptContext("respond");
respondContext->addPersistentTable("self", {{"location", "Norway"}, {"called", 0}});
callbacks.registerFunction("name", [](VariantList const& args) -> Variant { return "Hanz"; });
helloContext->setCallbacks("callbacks", callbacks);
respondContext->setCallbacks("callbacks", callbacks);
helloContext->invoke("doit");
respondContext->invoke("doit");
callbacks.registerFunction("name", [](VariantList const& args) -> Variant { return "Franz"; });
helloContext->setCallbacks("callbacks", callbacks);
respondContext->setCallbacks("callbacks", callbacks);
helloContext->invoke("doit");
respondContext->invoke("doit");
} catch (std::exception const& e) {
coutf("Exception caught: %s\n", e.what());
}
}

View file

@ -0,0 +1,85 @@
#include "StarNetStates.hpp"
using namespace Star;
void testStepSendReceive() {
NetSchema schema;
schema.addFixedPointField("position_x", NetType::VarInt, 0.1);
schema.addFixedPointField("position_y", NetType::VarInt, 0.1);
schema.finalize();
NetStepSender sender(schema);
sender.setStep(0);
sender.setFloat("position_x", 100.783);
sender.setFloat("position_y", 50.134);
ByteArray s1 = sender.writeFull();
coutf("sent packet of %s bytes\n", s1.size());
sender.setStep(1);
sender.setFloat("position_x", 100.5);
sender.setFloat("position_y", 49.938);
ByteArray s2 = sender.writeDelta(0);
coutf("sent packet of %s bytes\n", s2.size());
sender.setStep(2);
sender.setFloat("position_x", 100.289);
ByteArray s3 = sender.writeDelta(1);
coutf("sent packet of %s bytes\n", s3.size());
NetReceiver receiver(schema);
receiver.readFull(s1);
coutf("First value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
receiver.readDelta(s2);
coutf("Second value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
receiver.readDelta(s3);
coutf("Third value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
}
void testSyncSendReceive() {
DataStreamBuffer bufferStream;
NetSchema schema;
schema.addFixedPointField("position_x", NetType::VarInt, 0.1);
schema.addFixedPointField("position_y", NetType::VarInt, 0.1);
schema.finalize();
NetSyncSender sender(schema);
sender.setFloat("position_x", 100.783);
sender.setFloat("position_y", 50.134);
size_t s1 = sender.writeFull(bufferStream);
coutf("sent packet of %s bytes\n", s1);
sender.setFloat("position_x", 100.5);
sender.setFloat("position_y", 49.938);
size_t s2 = sender.writeDelta(bufferStream);
coutf("sent packet of %s bytes\n", s2);
sender.setFloat("position_x", 100.289);
size_t s3 = sender.writeDelta(bufferStream);
coutf("sent packet of %s bytes\n", s3);
bufferStream.seek(0);
NetReceiver receiver(schema);
receiver.readFull(bufferStream, s1);
coutf("First value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
receiver.readDelta(bufferStream, s2);
coutf("Second value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
receiver.readDelta(bufferStream, s3);
coutf("Third value received (%s, %s)\n", receiver.getFloat("position_x"), receiver.getFloat("position_y"));
}
int main(int argc, char** argv) {
testStepSendReceive();
testSyncSendReceive();
return 0;
}

View file

@ -0,0 +1,45 @@
#include "StarNetSocket.hpp"
using namespace Star;
int main(int argc, char** argv) {
class TestSockThread : public Thread {
public:
TestSockThread(NetSocketPtr ns) : Thread("TestSockThread"), m_netSocket(ns) {}
virtual void run() {
int count = 0;
coutf("starting\n");
// Just to test timing out, wait on a packet never sent.
if (!m_netSocket->waitPacket<ClientConnectPacket>(1000))
coutf("timed out waiting for bogus packet (expected)\n");
while (count < 10) {
m_netSocket->sendPacket(make_shared<ClientConnectPacket>());
if (m_netSocket->waitPacket<ClientConnectPacket>(1000)) {
++count;
coutf("packet received\n");
} else {
coutf("timed out\n");
}
}
coutf("received all packets!\n");
}
private:
NetSocketPtr m_netSocket;
};
auto pair = NetSocket::memorySocketPair();
TestSockThread testThread1(pair.first);
TestSockThread testThread2(pair.second);
testThread1.start();
testThread2.start();
testThread1.join();
testThread2.join();
return 0;
}

View file

@ -0,0 +1,48 @@
#include "StarCasting.hpp"
using namespace Star;
struct ClassA {
virtual ~ClassA() {}
};
struct ClassB : ClassA {
ClassB(int member) : member(member) {}
virtual ~ClassB() {}
int member;
};
int main(int argc, char** argv) {
ClassA* ptra = new ClassA();
ClassA* ptrb = new ClassB(42);
coutf("%s\n", is<ClassB>(ptra));
coutf("%s\n", is<ClassB>(ptrb));
coutf("%s\n", convert<ClassB>(ptrb)->member);
try {
// Expected to throw exception
coutf("%s\n", convert<ClassB>(ptra)->member);
} catch (std::exception const& e) {
coutf("Expected exception caught: %s\n", e.what());
}
shared_ptr<ClassA> sharedptra = make_shared<ClassA>();
shared_ptr<ClassA> sharedptrb = make_shared<ClassB>(42);
coutf("%s\n", is<ClassB>(sharedptra));
coutf("%s\n", is<ClassB>(sharedptrb));
coutf("%s\n", convert<ClassB>(sharedptrb)->member);
try {
// Expected to throw exception
coutf("%s\n", convert<ClassB>(sharedptra)->member);
} catch (std::exception const& e) {
coutf("Expected exception caught: %s\n", e.what());
}
delete ptra;
delete ptrb;
return 0;
}

View file

@ -0,0 +1,22 @@
#include "StarRandom.hpp"
#include "StarFormat.hpp"
#include "StarLexicalCast.hpp"
using namespace Star;
int main(int argc, char** argv) {
try {
uint64_t seed = 0;
if (argc == 2)
seed = lexicalCast<uint64_t>(argv[1]);
RandomSource rand(seed);
for (int i = 0; i < 10; ++i)
coutf("%s: %s\n", i, rand.randu32());
return 0;
} catch (std::exception const& e) {
coutf("Exception caught: %s\n", e.what());
return 1;
}
}

View file

@ -0,0 +1,15 @@
#include "StarSignalHandler.hpp"
#include "StarFormat.hpp"
using namespace Star;
void causeSegfault() {
volatile int* f = nullptr;
coutf("%s\n", *f);
}
int main() {
SignalHandler signalHandler;
causeSegfault();
return 0;
}

View file

@ -0,0 +1,52 @@
#include "StarSimpleDatabase.hpp"
#include "StarFile.hpp"
#include "StarRandom.hpp"
using namespace Star;
using namespace std;
const size_t MaxRecordSize = 10000;
const size_t RecordCount = 10000;
const size_t BlockSize = 2048;
int main(int argc, char** argv) {
SimpleDatabase db;
db.setIODevice(File::open("./simple.db", File::ReadWrite | File::Truncate));
db.setKeySize(8);
db.setBlockSize(BlockSize);
db.setAutoCommit(false);
db.open();
DataStreamBuffer key(8);
ByteArray value(MaxRecordSize, 0);
StreamOffset totalRecordSize = 0;
coutf("inserting values...\n");
for (size_t i = 0; i < RecordCount; ++i) {
key.seek(0);
key.write<uint32_t>(Random::randu32());
key.write<uint32_t>(Random::randu32());
size_t recordSize = Random::randf() * MaxRecordSize;
db.insert(key.data(), ByteArray(value.ptr(), recordSize));
totalRecordSize += recordSize + 8;
if (i % 1000 == 0)
db.commit();
}
coutf("done\n\n");
db.commit();
coutf("number of records: %s, total record size: %s\n", RecordCount, totalRecordSize);
coutf("total block count: %s, index block count: %s\n", db.blockCount(), db.indexCount());
StreamOffset totalFileSize = (StreamOffset)(db.blockCount()) * BlockSize + 256;
float indexOverhead = db.indexCount() * BlockSize / (float)totalFileSize * 100;
float totalOverhead = (totalFileSize - totalRecordSize) / (float)totalFileSize * 100;
coutf("index overhead: %s%%, total overhead: %s%%\n", indexOverhead, totalOverhead);
db.close();
}

View file

@ -0,0 +1,31 @@
#include "StarFormat.hpp"
using namespace Star;
void throwException() {
throw StarException("some exception");
}
void baz() {
throwException();
}
void bar() {
baz();
}
void foo() {
try {
bar();
} catch(std::exception const& e) {
throw StarException("some top-level exception", e);
}
}
int main(int argc, char** argv) {
try {
foo();
} catch(std::exception const& e) {
coutf("%s\n", e.what());
}
}

View file

@ -0,0 +1,62 @@
#include "StarStepInterpolation.hpp"
#include "StarRandom.hpp"
using namespace Star;
int main(int argc, char** argv) {
double serverStep = 0.0;
double dataPoint = 0.0;
StepStream<double> doubleStream;
doubleStream.setExtrapolation(15);
StepTracker stepTracker(6, 0.05);
// Simulate simple motion with some step skips, jitter, and pauses.
for (size_t i = 1; i < 200; ++i) {
// Produce a server step point.
if (i < 90)
dataPoint = i * 3;
else if (i >= 120 && i < 150)
dataPoint = (i - 30) * 3;
else if (i >= 150)
dataPoint = (270 - i) * 3;
else
dataPoint = -1.0f;
size_t doSteps = 0;
if (i == 50)
doSteps = 9;
else if (i == 51 || i == 52)
doSteps = 0;
else if (i % 11 == 0)
doSteps = 4;
else if (i % 19 == 0)
doSteps = 2;
else
doSteps = 3;
serverStep += 3.0;
// Consume the server point on the client, and do doSteps of client
// iterations.
stepTracker.heartbeat(serverStep);
if (dataPoint >= 0.0f) {
doubleStream.addDataPoint(stepTracker.leadStep(), dataPoint);
// coutf("%s %s\n", predictedStep, dataPoint);
} else {
doubleStream.heartbeat(stepTracker.leadStep());
}
for (size_t s = 0; s < doSteps; ++s) {
stepTracker.update(stepTracker.currentStep() + 1.0f);
doubleStream.setStep(stepTracker.currentStep());
coutf("%s\n", doubleStream.interpolate());
}
}
return 0;
}

View file

@ -0,0 +1,43 @@
#include "StarStringMap.hpp"
using namespace Star;
int main(int argc, char** argv) {
try {
// To test, we don't want the ptrs to remain valid
char keytmp[4];
StringMap<int> map;
{
StringMap<int> mapCopy;
strcpy(keytmp, "foo");
map.insert(keytmp, 1);
strcpy(keytmp, "boo");
map.insert(keytmp, 2);
strcpy(keytmp, "bob");
map.insert(keytmp, 3);
strcpy(keytmp, "fab");
map.insert(keytmp, 4);
map = mapCopy;
// Not making it in, using to test operator= and that refs remain valid,
// etc.
strcpy(keytmp, "som");
mapCopy.insert(keytmp, 5);
}
coutf("total keys: %s\n", map.size());
coutf("%s %s %s %s\n", map.get("foo"), map.get(String("boo")), map.get("bob"), map.get(String("fab")));
map.remove("foo");
map.remove("bob");
coutf("%s %s\n", map.get("boo"), map.get("fab"));
} catch (std::exception const& e) {
coutf("ERROR: Exception caught! %s\n", e.what());
}
}

View file

@ -0,0 +1,32 @@
#include "StarThread.hpp"
#include "StarFormat.hpp"
using namespace Star;
ConditionVariable cond;
Mutex mutex;
struct TestThread : Thread {
TestThread() : Thread("TestThread") {}
void run() {
MutexLocker locker(mutex);
for (int i = 0; i < 100; ++i) {
cond.wait(mutex, 5000);
std::cout << "stuff" << std::endl;
}
}
};
int main(int argc, char** argv) {
TestThread thread;
thread.start();
for (int i = 0; i < 100; ++i) {
Thread::sleep(1000);
MutexLocker locker(mutex);
cond.signal();
}
thread.join();
}

View file

@ -0,0 +1,104 @@
#include <fstream>
#include "StarString.hpp"
#include "StarFile.hpp"
#include "StarVariant.hpp"
using namespace Star;
using namespace std;
int main(int argc, char** argv) {
try {
String s1("This is a [日本語] Unicode String");
Variant v = Variant::parse("{ \"first\" : \"日本語\", \"second\" : \"foobar\\u02b0\" }");
cout << "Parsed variant: " << v.repr() << endl;
VariantMap vm;
vm["one"] = true;
vm["two"] = 22222222222222222;
vm["three"] = 3.3;
vm["four"] = "日本語";
vm["largeInt"] = 1234567890123456789L;
String s2 = Variant(vm).repr();
cout << "Map to json: " << s2 << endl;
cout << "json to map: " << Variant::parse(s2) << endl;
VariantList vl(4, Variant());
vl[0] = "foo";
vl[1] = 22222222222222222;
vl[2] = 3.3;
vl[3] = "日本語 bar";
String s3 = Variant(vl).repr();
cout << "List to json: " << s3 << endl;
cout << "json to list: " << Variant::parse(s3) << endl;
vm["five"] = vl;
cout << "Write to file: ./jsontest.txt" << endl;
ofstream ofile("./jsontest.txt");
Variant(vm).writeJson(ofile, true);
ofile << endl;
ofile.close();
cout << "Read from file: ./jsontest.txt" << endl;
ifstream ifile("./jsontest.txt");
cout << Variant(Variant::readJson(ifile)).repr(2) << endl;
ifile.close();
cout << "Write binary to file: ./jsontest.bin" << endl;
DataStream dataOs(File::open("./jsontest.bin", IODevice::Write));
dataOs << Variant(vm);
dataOs.device().close();
cout << "Read binary from file: ./jsontest.bin" << endl;
dataOs.device().open(IODevice::Read);
cout << dataOs.read<Variant>().repr(2) << endl;
dataOs.device().close();
cout << "Write binary to memory" << endl;
DataStreamBuffer dataBuffer;
dataBuffer << Variant(vm);
auto memData = dataBuffer.data();
cout << "Read binary from memory" << endl;
dataBuffer.reset(memData);
cout << dataBuffer.read<Variant>().repr(2) << endl;
Variant queryTest = Variant::parse(R"JSON(
{"foo" : [{}, {"bar" : {"baz" : [0, 1, 2] }}]}
)JSON");
coutf("query result: %s\n", queryTest.query("foo[1].bar.baz[2]"));
try {
queryTest.queryMap("foo[1].bar.baz[2]");
} catch (VariantException const& e) {
coutf("Expected exception caught: %s\n", e.message());
}
Variant v1 = VariantMap();
v1["foo"] = 88;
v1["bar"] = 1.0;
v1["baz"] = VariantList{1, 2, 3};
Variant v2 = v1;
v2["bar"] = Variant();
coutf("Variant v1 shoudl be different from variant v2 (checking CopyOnWrite)\n%s\n%s\n", v1.repr(2), v2.repr(2));
Variant v3 = VariantMap();
v3["foo"] = 88;
v3["bar"] = 1.0;
v3["baz"] = VariantList{1, 2, 3};
coutf("Variant v1 shoudl be identical to v3, though have different data: is %s\n", v1 == v3);
} catch (std::exception const& e) {
coutf("exception caught: %s\n", e.what());
return 1;
}
return 0;
}