aboutsummaryrefslogtreecommitdiff
path: root/src/value.c
blob: 1a7688086efd557d124b41aff1432fd46194d310 (plain)
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
#include "../include/value.h"
#include <string.h>

static uint64_t hash_range(const uint8_t *data, size_t size) {
    uint64_t result = 0xdec05eba;
    while(size) {
        result = ((result << 5) + result) + *data;
        ++data;
        --size;
    }
    return result;
}

uint64_t tsl_value_hash(const TslValue *key) {
    switch((TslType)key->type) {
        case TSL_TYPE_NULL:
            return 0;
        case TSL_TYPE_NUMBER:
            return *(uint64_t*)&key->data.number;
        case TSL_TYPE_STRING:
            return hash_range((uint8_t*)key->data.string->data, key->data.string->size);
        case TSL_TYPE_STRING_REF:
            return hash_range((uint8_t*)key->data.string_ref.data, key->data.string_ref.size);
        case TSL_TYPE_BOOL:
            return key->data.boolean;
        case TSL_TYPE_LIST:
            return (uint64_t)key->data.list;
        case TSL_TYPE_MAP:
            return (uint64_t)key->data.map;
        case TSL_TYPE_FUNCTION:
            return key->data.function;
        case TSL_TYPE_USERDATA:
            return (uint64_t)key->data.userdata;
    }
    return 0;
}

int tsl_value_equals(const TslValue *lhs, const TslValue *rhs) {
    if(lhs->type == rhs->type) {
        if(lhs->type == TSL_TYPE_STRING) {
            return lhs->data.string->size == rhs->data.string->size
                && memcmp(lhs->data.string->data, rhs->data.string->data, lhs->data.string->size) == 0;
        } else if(lhs->type == TSL_TYPE_STRING_REF) {
            return lhs->data.string_ref.size == rhs->data.string_ref.size
                && memcmp(lhs->data.string_ref.data, rhs->data.string_ref.data, lhs->data.string_ref.size) == 0;
        } else {
            return *(uint64_t*)&lhs->data == *(uint64_t*)&rhs->data;
        }
    } else if(lhs->type == TSL_TYPE_STRING && rhs->type == TSL_TYPE_STRING_REF) {
        return lhs->data.string->size == rhs->data.string_ref.size
                && memcmp(lhs->data.string->data, rhs->data.string_ref.data, lhs->data.string->size) == 0;
    } else if(lhs->type == TSL_TYPE_STRING_REF && rhs->type == TSL_TYPE_STRING) {
        return lhs->data.string_ref.size == rhs->data.string->size
                && memcmp(lhs->data.string_ref.data, rhs->data.string->data, lhs->data.string_ref.size) == 0;
    } else {
        return 0;
    }
}

void tsl_value_clear(TslValue *self) {
    memset(self, 0, sizeof(TslValue));
}