aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
authorrubenwardy <rubenwardy@gmail.com>2017-01-31 19:49:01 +0000
committerrubenwardy <rubenwardy@gmail.com>2017-02-04 22:07:55 +0000
commitf2aa2c6a986dec47856c49ae5f54fbf3c688e027 (patch)
treed12fbb3e62776efaafe059a7fdbfa9938e7298cd /src/util
parentc2e7b1f57941cb34cb7e3d71dc040fad53a64e3e (diff)
downloadminetest-f2aa2c6a986dec47856c49ae5f54fbf3c688e027.tar.gz
minetest-f2aa2c6a986dec47856c49ae5f54fbf3c688e027.tar.bz2
minetest-f2aa2c6a986dec47856c49ae5f54fbf3c688e027.zip
Add ItemStack key-value meta storage
Diffstat (limited to 'src/util')
-rw-r--r--src/util/serialize.cpp49
-rw-r--r--src/util/serialize.h7
2 files changed, 56 insertions, 0 deletions
diff --git a/src/util/serialize.cpp b/src/util/serialize.cpp
index 99cb990f1..61d369bc4 100644
--- a/src/util/serialize.cpp
+++ b/src/util/serialize.cpp
@@ -354,6 +354,55 @@ std::string deSerializeJsonString(std::istream &is)
return os.str();
}
+std::string serializeJsonStringIfNeeded(const std::string &s)
+{
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
+ return serializeJsonString(s);
+ }
+ return s;
+}
+
+std::string deSerializeJsonStringIfNeeded(std::istream &is)
+{
+ std::ostringstream tmp_os;
+ bool expect_initial_quote = true;
+ bool is_json = false;
+ bool was_backslash = false;
+ for (;;) {
+ char c = is.get();
+ if (is.eof())
+ break;
+
+ if (expect_initial_quote && c == '"') {
+ tmp_os << c;
+ is_json = true;
+ } else if(is_json) {
+ tmp_os << c;
+ if (was_backslash)
+ was_backslash = false;
+ else if (c == '\\')
+ was_backslash = true;
+ else if (c == '"')
+ break; // Found end of string
+ } else {
+ if (c == ' ') {
+ // Found end of word
+ is.unget();
+ break;
+ } else {
+ tmp_os << c;
+ }
+ }
+ expect_initial_quote = false;
+ }
+ if (is_json) {
+ std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
+ return deSerializeJsonString(tmp_is);
+ } else
+ return tmp_os.str();
+}
+
////
//// String/Struct conversions
////
diff --git a/src/util/serialize.h b/src/util/serialize.h
index 36324a675..e22434191 100644
--- a/src/util/serialize.h
+++ b/src/util/serialize.h
@@ -405,6 +405,13 @@ std::string serializeJsonString(const std::string &plain);
// Reads a string encoded in JSON format
std::string deSerializeJsonString(std::istream &is);
+// If the string contains spaces, quotes or control characters, encodes as JSON.
+// Else returns the string unmodified.
+std::string serializeJsonStringIfNeeded(const std::string &s);
+
+// Parses a string serialized by serializeJsonStringIfNeeded.
+std::string deSerializeJsonStringIfNeeded(std::istream &is);
+
// Creates a string consisting of the hexadecimal representation of `data`
std::string serializeHexString(const std::string &data, bool insert_spaces=false);