-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.c
117 lines (100 loc) · 1.86 KB
/
utils.c
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
106
107
108
109
110
111
112
113
114
115
116
117
/*
* Copyright (c) 2020-2021 Siddharth Chandrasekaran <sidcha.dev@gmail.com>
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdarg.h>
#include <stdio.h>
#include <stddef.h>
#include <ctype.h>
#include <stdlib.h>
#include <sys/time.h>
#include "utils.h"
//void gettimeofday (void){
//}
int randint(int limit)
{
int r;
int divisor = RAND_MAX / (limit + 1);
do {
r = rand() / divisor;
} while (r > limit);
return r;
}
uint32_t round_up_pow2(uint32_t v)
{
/* from the bit-twiddling hacks */
v -= 1;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v += 1;
return v;
}
int num_digits_in_number(int num)
{
int digits = 0, n = ABS(num);
while (n > 0) {
digits++;
n /= 10;
}
return digits;
}
__attribute__((format(printf, 3, 4)))
void hexdump(const void *p, size_t len, const char *fmt, ...)
{
size_t i;
va_list args;
char str[16 + 1] = {0};
const uint8_t *data = p;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf(" [%zu] =>\n 0000 %02x ", len, data[0]);
str[0] = isprint(data[0]) ? data[0] : '.';
for (i = 1; i < len; i++) {
if ((i & 0x0f) == 0) {
printf(" |%16s|", str);
printf("\n %04x ", i);
} else if((i & 0x07) == 0) {
printf(" ");
}
printf("%02x ", data[i]);
str[i & 0x0f] = isprint(data[i]) ? data[i] : '.';
}
if ((i &= 0x0f) != 0) {
if (i <= 8) printf(" ");
while (i < 16) {
printf(" ");
str[i++] = ' ';
}
printf(" |%16s|", str);
} else {
printf(" |%16s|", str);
}
printf("\n");
}
//int64_t usec_now()
//{/
// int64_t usec;
// struct timeval tv;
//
// gettimeofday(&tv, NULL);
// usec = tv.tv_sec * 1000L * 1000L + tv.tv_usec;
//
// return usec;
//}
//int64_t usec_since(int64_t last)
//{/
// return usec_now() - last;
//}
int64_t millis_now()
{
return (int64_t)(usec_now() / 1000LL);
}
int64_t millis_since(int64_t last)
{
return millis_now() - last;
}