json_loader.cpp 8.2 KB
Newer Older
1 2 3 4 5 6 7
#include "json_loader.h"

using namespace mgb;

template <typename T>
T* JsonLoader::Value::safe_cast() {
    T* ptr = (T*)(this);
8
    mgb_assert(nullptr != ptr, "cast ptr is null\n");
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    return ptr;
}

std::unique_ptr<JsonLoader::Value>& JsonLoader::Value::operator[](
        const std::string& key) {
    mgb_assert(Type::OBJECT == m_type);
    auto t = safe_cast<JsonLoader::ObjectValue>();
    return t->m_obj.at(key);
}

std::unique_ptr<JsonLoader::Value>& JsonLoader::Value::operator[](const size_t index) {
    mgb_assert(Type::ARRAY == m_type);
    auto t = safe_cast<JsonLoader::ArrayValue>();
    return t->m_obj[index];
}

std::map<std::string, std::unique_ptr<JsonLoader::Value>>& JsonLoader::Value::
        objects() {
    mgb_assert(Type::OBJECT == m_type);
    auto t = safe_cast<JsonLoader::ObjectValue>();
    return t->m_obj;
}

32 33 34 35 36 37
std::vector<std::string>& JsonLoader::Value::keys() {
    mgb_assert(Type::OBJECT == m_type);
    auto t = safe_cast<JsonLoader::ObjectValue>();
    return t->m_keys;
}

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
size_t JsonLoader::Value::len() {
    if (Type::ARRAY == m_type) {
        auto t = safe_cast<JsonLoader::ArrayValue>();
        return t->m_obj.size();
    } else if (Type::OBJECT == m_type) {
        auto t = safe_cast<JsonLoader::ObjectValue>();
        return t->m_obj.size();
    }
    return 0;
}

megdnn::SmallVector<std::unique_ptr<JsonLoader::Value>>& JsonLoader::Value::array() {
    mgb_assert(Type::ARRAY == m_type);
    auto t = safe_cast<JsonLoader::ArrayValue>();
    return t->m_obj;
}

double JsonLoader::Value::number() {
    mgb_assert(Type::NUMBER == m_type);
    auto t = safe_cast<JsonLoader::NumberValue>();
    return t->value();
}

61 62 63 64 65 66
bool JsonLoader::Value::Bool() {
    mgb_assert(Type::BOOL == m_type);
    auto t = safe_cast<JsonLoader::BoolValue>();
    return t->value();
}

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
std::string JsonLoader::Value::str() {
    if (Type::STRING == m_type) {
        auto t = safe_cast<StringValue>();
        return t->value();
    }
    return std::string();
}

void JsonLoader::expect(char c) {
    mgb_assert(c == (*m_buf));
    m_buf++;
}

void JsonLoader::skip_whitespace() {
    const char* p = m_buf;
82
    while (' ' == *p || '\t' == *p || '\n' == *p || '\r' == *p) {
83 84 85 86 87 88 89 90 91 92
        ++p;
    }
    m_buf = p;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::parse_object() {
    expect('{');
    skip_whitespace();

    std::unique_ptr<JsonLoader::Value> ret;
93 94
    std::unique_ptr<JsonLoader::ObjectValue> pObject =
            std::make_unique<JsonLoader::ObjectValue>();
95 96 97

    if ('}' == *m_buf) {
        m_buf = m_buf + 1;
98
        ret = std::move(pObject);
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        return ret;
    }

    while (true) {
        std::unique_ptr<JsonLoader::Value> key = parse_string();
        if (m_state != State::OK) {
            return ret;
        }

        skip_whitespace();
        if (':' != (*m_buf)) {
            m_state = State::MISS_COLON;
            return ret;
        }
        m_buf++;
        skip_whitespace();

        std::unique_ptr<JsonLoader::Value> pVal = parse_value();
        if (m_state != State::OK) {
            return ret;
        }

        if (pObject->m_obj.find(pVal->str()) != pObject->m_obj.end()) {
            m_state = State::KEY_NOT_UNIQUE;
            return ret;
        }

        pObject->m_obj.insert(std::make_pair(key->str(), std::move(pVal)));
127
        pObject->m_keys.push_back(key->str());
128 129 130 131 132 133 134 135 136 137 138 139 140

        skip_whitespace();
        if (',' == (*m_buf)) {
            m_buf++;
            skip_whitespace();
        } else if ('}' == (*m_buf)) {
            m_buf++;
            break;
        } else {
            m_state = State::MISS_BRACE;
            break;
        }
    }
141
    ret = std::move(pObject);
142 143 144 145 146 147 148
    return ret;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::parse_array() {
    expect('[');
    skip_whitespace();
    std::unique_ptr<JsonLoader::Value> ret;
149 150
    std::unique_ptr<JsonLoader::ArrayValue> pArray =
            std::make_unique<JsonLoader::ArrayValue>();
151 152 153 154

    if (']' == *m_buf) {
        m_buf = m_buf + 1;

155
        ret = std::move(pArray);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        return ret;
    }

    while (true) {
        std::unique_ptr<JsonLoader::Value> pVal = parse_value();
        if (m_state != State::OK) {
            mgb_assert(0, "parse value failed during pase array");
            return ret;
        }

        pArray->m_obj.emplace_back(pVal.get());
        pVal.release();

        skip_whitespace();
        if (',' == *m_buf) {
            m_buf++;
            skip_whitespace();
        } else if (']' == *m_buf) {
            m_buf++;
            break;
        } else {
            m_state = State::BAD_ARRAY;
            return ret;
        }
    }

182
    ret = std::move(pArray);
183 184 185 186 187
    return ret;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::parse_string() {
    expect('\"');
188 189
    std::unique_ptr<JsonLoader::StringValue> pStr =
            std::make_unique<JsonLoader::StringValue>();
190 191 192 193 194 195 196 197 198 199 200 201

    const char* p = m_buf;
    while (true) {
        if (*p == '\"') {
            p++;
            break;
        } else {
            pStr->m_value += (*p);
            p++;
        }
    }
    m_buf = p;
202
    std::unique_ptr<JsonLoader::Value> ret = std::move(pStr);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    return ret;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::parse_number() {
    const char* p = m_buf;

    auto loop_digit = [this](const char*& p) {
        if (not std::isdigit(*p)) {
            m_state = State::BAD_DIGIT;
            return;
        }
        while (std::isdigit(*p)) {
            p++;
        }
        return;
    };

220
    if ('-' == *p)
221
        p++;
222
    if ('0' == *p)
223 224 225 226
        p++;
    else {
        loop_digit(std::ref(p));
    }
227
    if ('.' == *p) {
228 229 230 231
        p++;
        loop_digit(std::ref(p));
    }

232
    if ('e' == *p || 'E' == *p) {
233
        p++;
234
        if ('+' == *p || '-' == *p)
235 236 237
            p++;
        loop_digit(std::ref(p));
    }
238 239
    std::unique_ptr<JsonLoader::NumberValue> pNum =
            std::make_unique<JsonLoader::NumberValue>();
240 241 242 243
    pNum->m_value = strtod(m_buf, nullptr);

    m_buf = p;

244
    std::unique_ptr<JsonLoader::Value> ret = std::move(pNum);
245 246 247 248 249 250 251 252 253 254 255
    return ret;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::parse_value() {
    switch (*m_buf) {
        case '[':
            return parse_array();
        case '{':
            return parse_object();
        case '\"':
            return parse_string();
256 257 258 259
        case 't':
            return parse_bool();
        case 'f':
            return parse_bool();
260 261 262 263 264 265 266 267 268
        case '\0':
            m_state = State::BAD_TYPE;
            break;
        default:
            return parse_number();
    }
    return nullptr;
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
std::unique_ptr<JsonLoader::Value> JsonLoader::parse_bool() {
    const char* p = m_buf;
    std::string value;
    if ('t' == *p) {
        value = "";
        for (size_t idx = 0; idx < 4; ++idx) {
            value += *p++;
        }
    } else if ('f' == *p) {
        value = "";
        for (size_t idx = 0; idx < 5; ++idx) {
            value += *p++;
        }
    }
    bool val = false;
    if ("true" == value) {
        val = true;
    } else if ("false" == value) {
        val = false;
    } else {
        mgb_log_error("invalid value: %s for possible bool value", value.c_str());
    }

    std::unique_ptr<JsonLoader::BoolValue> pBool =
            std::make_unique<JsonLoader::BoolValue>();
    pBool->m_value = val;
    m_buf = p;
    std::unique_ptr<JsonLoader::Value> ret = std::move(pBool);
    return ret;
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
std::unique_ptr<JsonLoader::Value> JsonLoader::load(
        const char* content, const size_t size) {
    m_buf = content;
    skip_whitespace();
    std::unique_ptr<JsonLoader::Value> value = parse_value();
    skip_whitespace();

    if (m_state != State::OK) {
        return nullptr;
    }
    mgb_assert(size == static_cast<size_t>(m_buf - content));

    return value;
}

std::unique_ptr<JsonLoader::Value> JsonLoader::load(const char* path) {
    std::unique_ptr<std::FILE, void (*)(std::FILE*)> fin(
            std::fopen(path, "rb"), [](std::FILE* fp) { std::fclose(fp); });

    mgb_assert(fin.get(), "failed to open %s: %s", path, strerror(errno));
    std::fseek(fin.get(), 0, SEEK_END);
    const size_t size = ftell(fin.get());
    std::fseek(fin.get(), 0, SEEK_SET);

324
    std::vector<char> buf(size + 1);
325

326
    auto nr = std::fread(buf.data(), 1, size, fin.get());
327 328
    mgb_assert(nr == size);

329
    return load(buf.data(), size);
330
}