-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
98 lines (83 loc) · 1.73 KB
/
utils.c
File metadata and controls
98 lines (83 loc) · 1.73 KB
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
#include "utils.h"
void* safeMalloc(size_t size, char *msg)
{
void* ptr = malloc(size);
if (!ptr)
{
perror(msg);
exit(1);
}
return ptr;
}
void* safeCalloc(size_t nmemb, size_t size, char *msg)
{
void* ptr = calloc(nmemb, size);
if (!ptr)
{
perror(msg);
exit(1);
}
return ptr;
}
void* safeRealloc(void *p, size_t size, char *msg)
{
void* ptr = realloc(p, size);
if (!ptr)
{
perror(msg);
exit(1);
}
return ptr;
}
void daIsNullCheck(DynamicArray *da)
{
if (!da)
{
fprintf(stderr, "Error: NULL dynamic array\n");
exit(1);
}
}
bool daNeedsResize(size_t size, size_t capacity)
{
return size == capacity;
}
bool daIndexInBounds(size_t size, size_t idx)
{
return idx < size;
}
size_t tensorComputeSize(size_t ndim, const size_t *shape)
{
size_t size = 1;
for (size_t i = 0; i < ndim; i++)
size *= shape[i];
return size;
}
void tensorComputeStrides(size_t ndim, const size_t *shape, size_t *strides)
{
strides[ndim - 1] = 1;
for (size_t i = ndim - 1; i-- > 0; )
strides[i] = strides[i + 1] * shape[i + 1];
}
void tensorIsNullCheck(Tensor *t)
{
if (!t)
{
fprintf(stderr, "Error: NULL tensor\n");
exit(1);
}
}
void linearToIndices(size_t linear, const size_t *shape, const size_t *strides, size_t ndim, size_t *out)
{
for (size_t i = 0; i < ndim; i++)
{
out[i] = linear / strides[i];
linear %= strides[i];
}
}
size_t indicesToLinear(const size_t *indices, const size_t *strides, size_t ndim)
{
size_t linear = 0;
for (size_t i = 0; i < ndim; i++)
linear += indices[i] * strides[i];
return linear;
}