1 /* copyright 2016 Apache 2 sddekit authors */
5 /* auto-allocating array */
6 typedef struct mem_data
{
9 uint32_t n_sample
, capacity
, nx
, nc
;
14 mem_get_n_sample(sd_out_mem
*out
)
16 return ((mem_data
*) out
->ptr
)->n_sample
;
20 mem_get_nx(sd_out_mem
*out
)
22 return ((mem_data
*) out
->ptr
)->nx
;
26 mem_get_nc(sd_out_mem
*out
)
28 return ((mem_data
*) out
->ptr
)->nc
;
32 mem_get_xs(sd_out_mem
*out
)
34 return ((mem_data
*) out
->ptr
)->xs
;
38 mem_get_cs(sd_out_mem
*out
)
40 return ((mem_data
*) out
->ptr
)->cs
;
44 mem_get_out(sd_out_mem
*out
)
46 return &(((mem_data
*)out
->ptr
)->out_if
);
50 mem_get_capacity(sd_out_mem
*out
)
52 return ((mem_data
*)out
->ptr
)->capacity
;
58 mem_data
*d
= out
->ptr
;
67 mem_apply(sd_out
*out
, double t
,
68 uint32_t nx
, double * restrict x
,
69 uint32_t nc
, double * restrict c
)
71 mem_data
*d
= out
->ptr
;
78 err
= (d
->xs
= sd_malloc (sizeof(double)*nx
))==NULL
;
79 err
|= (d
->cs
= sd_malloc (sizeof(double)*nc
))==NULL
;
81 sd_err("failed to allocate memory.");
82 if (d
->xs
!=NULL
) sd_free(d
->xs
);
83 if (d
->cs
!=NULL
) sd_free(d
->cs
);
88 memcpy(d
->xs
+ d
->n_sample
*nx
, x
, sizeof(double)*nx
);
89 memcpy(d
->cs
+ d
->n_sample
*nc
, c
, sizeof(double)*nc
);
91 if (d
->n_sample
==d
->capacity
) {
94 x_
= sd_realloc (d
->xs
, sizeof(double)*nx
*2*d
->capacity
);
96 sd_err("failed to allocate memory.");
99 /* save new ptr in case c_ realloc fails, free can still
104 c_
= sd_realloc (d
->cs
, sizeof(double)*nc
*2*d
->capacity
);
106 sd_err("failed to allocate memory.");
117 mem_defaults
= { .out
= &mem_get_out
, .get_nx
=&mem_get_nx
, .get_nc
=&mem_get_nc
,
118 .get_n_sample
=&mem_get_n_sample
, .get_capacity
=&mem_get_capacity
,
119 .get_xs
=&mem_get_xs
, .get_cs
=&mem_get_cs
123 mem_out_defaults
= { .free
= &mem_free
,.apply
= &mem_apply
};
129 if ((d
= sd_malloc(sizeof(mem_data
))) == NULL
)
131 sd_err("alloc failed for new mem output.");
138 d
->mem_if
= mem_defaults
;
139 d
->out_if
= mem_out_defaults
;
140 d
->out_if
.ptr
= d
->mem_if
.ptr
= d
;