summaryrefslogtreecommitdiff
path: root/c_src/util.c
blob: 76294ebb9aed9e3bed0fdfcee71ac262f0c20c1b (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * Copyright (c) 2015, NORDUnet A/S.
 * See LICENSE for licensing information.
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <err.h>
#include <nettle/sha2.h>
#include "erlport.h"
#include "permdb.h"
#include "util.h"

void
set_error(char **error, const char *format, ...)
{
        va_list args;
        int ret;

        if (error == NULL) {
                return;
        }

        va_start(args, format);
        char *formatted = NULL;
        ret = vasprintf (&formatted, format, args);
        if (ret == -1) {
                fprintf(stderr, "vasprintf error\n");
                return;
        }
        if (*error) {
                free(*error);
        }
        fprintf(stderr, "error: %s\n", formatted);
        *error = formatted;
        va_end(args);
}

int
calc_padding(int offset, int alignment)
{
        int misalign = offset % alignment;
        if (misalign == 0) {
                return 0;
        }
        return alignment - misalign;
}

void
print_entry(node_object node)
{
        for (int i = 0; i < entriespernode; i++) {
                fprintf(stderr, " %016llx", (long long unsigned int)node.data[i]);
        }
        fprintf(stderr, "\n");
}

void
print_hex(const void *data, int length)
{
        int i;
        for (i = 0; i < length; i++) {
                fprintf(stderr, "%02X ", ((unsigned char *)data)[i]);
        }
        fprintf(stderr, "\n");
}

uint64_t
read_host64(void *ptr)
{
        uint64_t data;

        memcpy(&data, ptr, sizeof(data));

        return data;
}

uint32_t
read_be32(void *ptr)
{
        uint32_t data;

        memcpy(&data, ptr, sizeof(data));

        return ntohl(data);
}

uint16_t
read_be16(void *ptr)
{
        uint16_t data;

        memcpy(&data, ptr, sizeof(data));

        return ntohs(data);
}