Dict_ut.cpp 2.07 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
/* Copyright 2015 the SumatraPDF project authors (see AUTHORS file).
   License: Simplified BSD (see COPYING.BSD) */

#include "BaseUtil.h"
#include "Dict.h"

// must be last due to assert() over-write
#include "UtAssert.h"

#define LETTERS "abcdefghijklmnopqrtswzABCDEFGHIJLMNOPQRTSWZ0123456789"

static inline char GenRandChar()
{
    return LETTERS[rand() % dimof(LETTERS)];
}

static char *GenRandomString()
{
    static char buf[256];
    int len = 1 + (rand() % (dimof(buf) - 4)); // 4 just in case, 2 should be precise value

    for (int i=0; i<len; i++) {
        buf[i] = GenRandChar();
    }
    buf[len] = 0;
    return &buf[0];
}

void DictTestMapStrToInt()
{
    dict::MapStrToInt d(4); // start small so that we can test resizing
    bool ok;
    int val;

    utassert(0 == d.Count());
    ok = d.Get("foo", &val);
    utassert(!ok);
    ok = d.Remove("foo", nullptr);
    utassert(!ok);

    ok = d.Insert("foo", 5, nullptr);
    utassert(ok);
    utassert(1 == d.Count());
    ok = d.Get("foo", &val);
    utassert(ok);
    utassert(val == 5);
    ok = d.Insert("foo", 8, &val);
    utassert(!ok);
    utassert(val == 5);
    ok = d.Get("foo", &val);
    utassert(ok);
    utassert(val == 5);
    ok = d.Get("bar", &val);
    utassert(!ok);

    val = 0;
    ok = d.Remove("foo", &val);
    utassert(ok);
    utassert(val == 5);
    utassert(0 == d.Count());

    srand((unsigned int)time(nullptr));
    Vec<char *> toRemove;
    for (int i=0; i < 1024; i++) {
        char *k = GenRandomString();
        ok = d.Insert(k, i, nullptr);
        // no guarantee that the string is unique, so Insert() doesn't always succeeds
        if (!ok)
            continue;
        toRemove.Append(str::Dup(k));
        utassert(toRemove.Count() == d.Count());
        ok = d.Get(k, &val);
        CrashIf(!ok);
        CrashIf(i != val);
    }
    for (const char *k : toRemove) {
        ok = d.Remove(k, nullptr);
        utassert(ok);
    }
    toRemove.FreeMembers();
}

void DictTest()
{
    DictTestMapStrToInt();
}