CoreUtils/JString.cpp
2024-12-11 09:55:40 -08:00

123 lines
3.5 KiB
C++

#include "JString.h"
#include "Exception.h"
namespace coreutils {
std::ostream &operator<<(std::ostream &os, const JString::Proxy &proxy) {
ZString tempkey = proxy.key;
ZString temp = proxy.jstring.find(tempkey);
os << temp;
return os;
}
JString::JString() : MString("{}") {}
void JString::set(ZString &path, ZString &value) {
reset();
if(locate(path)) {
push();
if(ifNext("\"")) {
ZString old = getTokenExclude("\"");
pop();
remove(offset(), old.getLength() + 2);
MString key;
key << "\"" << value << "\"";
insert(key, offset());
} else {
pop();
throw coreutils::Exception("Fix me to accept integer type.");
}
} else {
std::cout << "[" << unparsed() << "] >" << value << "<" << std::endl;
MString key;
if(notfirst)
key << ",";
// TODO: The value added must be parsed down to remove all whitespace.
value.push();
value.skipWhitespace();
if(value.startsWith("["))
key << "\"" << path << "\":" << value;
else if(value.startsWith("{"))
key << "\"" << path << "\":" << value;
else
key << "\"" << path << "\":" << "\"" << value << "\"";
value.pop();
insert(key, offset());
}
}
ZString JString::find(ZString &path) {
reset();
if(locate(path)) {
if(ifNext("\""))
return getTokenExclude("\"");
// TODO: Handle numbers that are not in double quotes.
else if(startsWith("["))
return getContainer();
else if(startsWith("{"))
return getContainer();
}
return ZString();
}
bool JString::locate(ZString &path) {
path.split(".", 1);
notfirst = false;
if(ifNext("{")) {
while(startsWith("\"")) {
notfirst = true;
ZString label;
ZString value;
if(ifNext("\"")) {
label = getTokenExclude("\"");
ifNext("\"");
} else
throw coreutils::Exception("Labels must be contained in double quotes.");
if(ifNext(":")) {
if(label == path[0]) {
if(path.getList().size() == 1) {
// std::cout << "found cursor: " << unparsed() << std::endl;
return true;
}
return locate(path[1]);
}
// std::cout << "+++" << unparsed() << std::endl;
if(startsWith("\"")) {
getContainer();
} else if(startsWith("[")) {
getContainer();
} else if(startsWith("{")) {
getContainer();
} else {
throw coreutils::Exception("Unrecognized data type.");
}
ifNext(",");
} else
throw coreutils::Exception("Expected colon after label.");
}
} else if(ifNext("[")) {
ZString label = path[0].getTokenExclude("[");
path[0].ifNext("[");
ZString key = path[0].getTokenExclude("=");
path[0].ifNext("=");
ZString value = path[0].getTokenExclude("]");
while(!ifNext("]")) {
push();
ZString check = find(key);
pop();
if(check.equals(value)) {
return locate(label);
} else {
getContainer();
ifNext(",");
}
}
}
// std::cout << "not found cursor: " << unparsed() << std::endl;
return false;
}
}