Data-MessagePack-Stream

 view release on metacpan or  search on metacpan

msgpack-3.3.0/example/c/jsonconv.c  view on Meta::CPAN

    return length - aux_buffer_size;
}
#undef PRINT_JSONSTR_CALL

static void test(const char *name, const char *input, const char *expect)
{
    msgpack_sbuffer sbuf;
    {
        // pack
        msgpack_packer pk;
        msgpack_sbuffer_init(&sbuf);
        msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
        if (msgpack_pack_jsonstr(&pk, input) < 0) {
            msgpack_sbuffer_destroy(&sbuf);
            printf("%s: invalid json string.\n", name);
            return;
        }
    }

    {
        // unpack
#define MAX_JSONLEN 1024
        msgpack_zone z;
        msgpack_object obj;
        size_t jsonstrlen = MAX_JSONLEN - 1;
        char jsonparsed[MAX_JSONLEN];

        msgpack_zone_init(&z, jsonstrlen);
        msgpack_unpack(sbuf.data, sbuf.size, NULL, &z, &obj);
        jsonstrlen = msgpack_object_print_jsonstr(jsonparsed, jsonstrlen, obj);
        jsonparsed[jsonstrlen] = '\0';

        //compare input and output
        if (expect == NULL) {
            expect = input;
        }
        if (strcmp(expect, jsonparsed) == 0) {
            printf("%s: ok\n", name);
        } else {
            printf("%s: failed\n", name);
        }
        msgpack_zone_destroy(&z);
    }
    msgpack_sbuffer_destroy(&sbuf);
}

int main()
{
    test("null", "null", NULL);
    test("boolean", "false", NULL);
    test("single string", "\"frsyuki\"", NULL);
    test("single number", "\"100\"", NULL);
    test("space", "[{\"valuespace\":\"\",\"\":\"keyspace\"},\"\",[\"\"]]", NULL);
    test("quote", "\"My name is Tom (\\\"Bee\\\") Kobe\"", NULL);
    test("escape", "\"\\\\b\\f\\n\\r\\t\"", NULL);
    test("escape2", "\"\b\f\n\r\t\"", "\"\\b\\f\\n\\r\\t\"");
    test("map", "{\"name\":\"Tom (\\\"Bee\\\") Kobe\",\"type\":\"image\",\"data\":{\"width\":360,\"height\":460,\"title\":\"View me\",\"ips\":[116,943,256,711]}}", NULL);
    test("array", "[\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"]", NULL);
    test("number array", "[[101,121,-33],[119,911,171],[0,2,-3]]", NULL);
    test("mix array", "[{\"name\":\"Tom\",\"city\":\"London\",\"country\":\"UK\",\"longitude\":23},{\"name\":\"Jack\",\"city\":\"Birmingham\",\"country\":\"UK\",\"longitude\":-22}]", NULL);
    test("unicode", "\"\\u5C71\\u5DDD\\u7570\\u57DF\\u98A8\\u6708\\u540C\\u5929\"", "\"山川異域風月同天\"");
    test("utf8", "\"山川異域風月同天\"", NULL);
    test("double", "12.34", "12.340000");

    return 0;
}



( run in 2.501 seconds using v1.01-cache-2.11-cpan-97f6503c9c8 )