-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfdf.c
119 lines (97 loc) · 2.6 KB
/
fdf.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
118
119
#include "fdf.h"
#include "fdf_types_full.h"
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
/*
This function reads the file and stores the data in storage
that it allocates itself
*/
int fdf_init_grid_meta( const fdf_template *templ,
fdf_grid_meta ***grid_specs )
{
/* This function can abuse the memory layout of grid_specs.
It should simply be an array with one or two pointers to grid_specs.
Make the memory block contiguous.
*/
int dim = templ->dimension;
*grid_specs = malloc( dim*sizeof(fdf_grid_meta*) );
if( !(*grid_specs) ){
return FDF_MALLOC_FAILED;
}
fdf_grid_meta *grid_specs_ = malloc( dim*sizeof(fdf_grid_meta) );
fprintf( stderr, "grid_specs_ lives at %p\n", (void*)grid_specs_ );
if( !grid_specs_ ){
free(grid_specs);
return FDF_MALLOC_FAILED;
}
(*grid_specs)[0] = grid_specs_;
if( dim == 2 ){
(*grid_specs)[1] = grid_specs_ + 1;
}
return FDF_SUCCESS;
}
int fdf_destroy_grid_meta( fdf_grid_meta **grid_specs )
{
// grid_specs[0] points to a malloc'ed pointer:
free( grid_specs[0] );
free( grid_specs );
return FDF_SUCCESS;
}
int fdf_init_grid( const fdf_template *templ,
fdf_grid_meta **grid_specs,
void ***grids )
{
*grids = malloc( sizeof(void**) );
if( !(*grids) ){
return FDF_MALLOC_FAILED;
}
for( int i = 0; i < templ->dimension; ++i ){
unsigned int type = grid_specs[i]->type;
int size = grid_specs[i]->size;
size_t alloc_size = fdf_data_type_to_ptr_size( type );
(*grids)[i] = malloc( alloc_size*size );
if( !(*grids)[i] ){
return FDF_MALLOC_FAILED;
}
}
return FDF_SUCCESS;
}
int fdf_init_data( const fdf_template *templ,
const fdf_grid_meta *grid_specs, void **data )
{
size_t n_elements = grid_specs[0].size;
if( templ->dimension == 2 ) n_elements *= grid_specs[1].size;
size_t alloc_size = fdf_data_type_to_ptr_size( templ->data_type );
*data = malloc( alloc_size*n_elements );
if( !(*data) ){
return FDF_MALLOC_FAILED;
}
/* After malloc-ing data it is the same as just calling read.
That is up to the user to do. */
return FDF_SUCCESS;
}
int fdf_destroy_grid( const fdf_template *templ, void **grids )
{
for( int i = 0; i <templ->dimension; ++i ){
free(grids[i]);
}
free(grids);
return FDF_SUCCESS;
}
int fdf_destroy_data( void *data )
{
free(data);
return FDF_SUCCESS;
}
int fdf_destroy_grids( int dimension, void ***grids, int **grid_sizes,
unsigned int **grid_types )
{
for( int i = 0; i < dimension; ++i ){
free((*grids)[i]);
}
free(*grids);
free(*grid_sizes);
free(*grid_types);
return FDF_SUCCESS;
}