| 1 | /* |
| 2 | This file is part of the GVars3 Library. |
| 3 | |
| 4 | Copyright (C) 2005 The Authors |
| 5 | |
| 6 | This library is free software, see LICENSE file for details |
| 7 | */ |
| 8 | |
| 9 | #include "gvars3/serialize.h" |
| 10 | #include <vector> |
| 11 | |
| 12 | using namespace std; |
| 13 | |
| 14 | |
| 15 | namespace GVars3 |
| 16 | { |
| 17 | namespace serialize |
| 18 | { |
| 19 | std::string to_string(const std::string& s, bool) |
| 20 | { |
| 21 | ostringstream os; |
| 22 | os << "\""; |
| 23 | |
| 24 | for(size_t i=0; i < s.size(); i++) |
| 25 | { |
| 26 | if(s[i] == '\\') |
| 27 | os << "\\\\"; |
| 28 | else if(s[i] == '\n') |
| 29 | os << "\\n"; |
| 30 | else |
| 31 | os << s[i]; |
| 32 | } |
| 33 | |
| 34 | os << "\""; |
| 35 | return os.str(); |
| 36 | } |
| 37 | |
| 38 | string FromStream<string>::from(istream& in) |
| 39 | { |
| 40 | string s; |
| 41 | |
| 42 | bool quoted=0; |
| 43 | int c; |
| 44 | |
| 45 | //Eat whitespace |
| 46 | in >> ws; |
| 47 | |
| 48 | if((c=in.get()) == EOF) |
| 49 | return s; |
| 50 | |
| 51 | if(c == '"') |
| 52 | quoted=1; |
| 53 | else |
| 54 | in.unget(); |
| 55 | |
| 56 | //This variable holds an escape sequence in progress. |
| 57 | //empty means no escaping. |
| 58 | string escape; |
| 59 | |
| 60 | for(;;) |
| 61 | { |
| 62 | c = in.get(); |
| 63 | if(c == EOF || (quoted && escape.empty() && c == '"')) |
| 64 | break; |
| 65 | else if(escape.empty() && c == '\\') |
| 66 | escape = "\\"; |
| 67 | else if(!escape.empty()) |
| 68 | escape += c; |
| 69 | else |
| 70 | s += c; |
| 71 | |
| 72 | //Check escapes |
| 73 | if(escape == "\\\\") |
| 74 | { |
| 75 | s+="\\"; |
| 76 | escape.clear(); |
| 77 | } |
| 78 | else if(escape == "\\n") |
| 79 | { |
| 80 | s+="\n"; |
| 81 | escape.clear(); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | //Append any trailing parts of an escape sequence |
| 86 | s += escape; |
| 87 | |
| 88 | return s; |
| 89 | } |
| 90 | |
| 91 | int check_stream(std::istream& i) |
| 92 | { |
| 93 | if(i.good()) |
| 94 | return 0; |
| 95 | |
| 96 | if(i.bad() || (i.fail() && !i.eof())) |
| 97 | { |
| 98 | return -i.tellg(); |
| 99 | } |
| 100 | return 0; |
| 101 | } |
| 102 | |
| 103 | } |
| 104 | |
| 105 | |
| 106 | } |