Debian Codegraph @

matio-1.5.30/src/mat.c

raw symbols SCIP
1 /** @file mat.c
2 * Matlab MAT file functions
3 * @ingroup MAT
4 */
5 /*
6 * Copyright (c) 2015-2026, The matio contributors
7 * Copyright (c) 2005-2014, Christopher C. Hulbert
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright notice, this
14 * list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright notice,
17 * this list of conditions and the following disclaimer in the documentation
18 * and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /* FIXME: Implement Unicode support */
33 #include "matio_private.h"
34 #include "mat5.h"
35 #include "mat4.h"
36 #if defined(MAT73) && MAT73
37 #include "mat73.h"
38 #endif
39 #include "safe-math.h"
40 #include <assert.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <stdio.h>
44 #include <math.h>
45 #include <time.h>
46 #if HAVE_INTTYPES_H
47 #define __STDC_FORMAT_MACROS
48 #include <inttypes.h>
49 #endif
50 #if ( defined(_WIN64) || defined(_WIN32) ) && !defined(__CYGWIN__)
51 #include <io.h>
52 #endif
53 #if defined(_MSC_VER) || defined(__MINGW32__)
54 #define SIZE_T_FMTSTR "Iu"
55 #define strdup _strdup
56 #else
57 #define SIZE_T_FMTSTR "zu"
58 #endif
59
60 /*
61 *===================================================================
62 * Private Functions
63 *===================================================================
64 */
65
66 #define MAT_MKTEMP_DIR "/tmp/"
67 #define MAT_MKTEMP_TPL "XXXXXX"
68 #define MAT_MKTEMP_FILE "/temp.mat"
69
70 #define MAT_MKTEMP_BUF_SIZE \
71 (sizeof(MAT_MKTEMP_DIR) + sizeof(MAT_MKTEMP_TPL) + sizeof(MAT_MKTEMP_FILE) - 2)
72
73 static char *
74 Mat_mktemp(char *path_buf, char *dir_buf)
75 {
76 char *ret = NULL;
77
78 *path_buf = '\0';
79 *dir_buf = '\0';
80
81 #if ( defined(_WIN64) || defined(_WIN32) ) && !defined(__CYGWIN__)
82 strncpy(path_buf, MAT_MKTEMP_TPL, MAT_MKTEMP_BUF_SIZE - 1);
83 path_buf[MAT_MKTEMP_BUF_SIZE - 1] = '\0';
84 if ( NULL != _mktemp(path_buf) )
85 ret = path_buf;
86 #else
87 /* On Linux, using mktemp() causes annoying linker errors that can't be
88 suppressed. So, create a temporary directory with mkdtemp() instead,
89 and then just always use the same hardcoded filename inside that temp dir.
90 */
91 strncpy(dir_buf, MAT_MKTEMP_DIR MAT_MKTEMP_TPL, MAT_MKTEMP_BUF_SIZE - 1);
92 dir_buf[MAT_MKTEMP_BUF_SIZE - 1] = '\0';
93 if ( NULL != mkdtemp(dir_buf) ) {
94 strncpy(path_buf, dir_buf, MAT_MKTEMP_BUF_SIZE - 1);
95 path_buf[MAT_MKTEMP_BUF_SIZE - 1] = '\0';
96 strncat(path_buf, MAT_MKTEMP_FILE, MAT_MKTEMP_BUF_SIZE - strlen(path_buf) - 1);
97 ret = path_buf;
98 }
99 #endif
100
101 return ret;
102 }
103
104 static int
105 ReadData(mat_t *mat, matvar_t *matvar)
106 {
107 if ( mat == NULL || matvar == NULL || mat->fp == NULL )
108 return MATIO_E_BAD_ARGUMENT;
109 else if ( mat->version == MAT_FT_MAT5 )
110 return Mat_VarRead5(mat, matvar);
111 #if defined(MAT73) && MAT73
112 else if ( mat->version == MAT_FT_MAT73 )
113 return Mat_VarRead73(mat, matvar);
114 #endif
115 else if ( mat->version == MAT_FT_MAT4 )
116 return Mat_VarRead4(mat, matvar);
117 return MATIO_E_FAIL_TO_IDENTIFY;
118 }
119
120 static void
121 Mat_PrintNumber(enum matio_types type, const void *data)
122 {
123 switch ( type ) {
124 case MAT_T_DOUBLE:
125 printf("%g", *(double *)data);
126 break;
127 case MAT_T_SINGLE:
128 printf("%g", *(float *)data);
129 break;
130 #ifdef HAVE_MAT_INT64_T
131 case MAT_T_INT64:
132 #if HAVE_INTTYPES_H
133 printf("%" PRIi64, *(mat_int64_t *)data);
134 #elif defined(_MSC_VER) && _MSC_VER >= 1200
135 printf("%I64i", *(mat_int64_t *)data);
136 #elif defined(HAVE_LONG_LONG_INT)
137 printf("%lld", (long long)(*(mat_int64_t *)data));
138 #else
139 printf("%ld", (long)(*(mat_int64_t *)data));
140 #endif
141 break;
142 #endif
143 #ifdef HAVE_MAT_UINT64_T
144 case MAT_T_UINT64:
145 #if HAVE_INTTYPES_H
146 printf("%" PRIu64, *(mat_uint64_t *)data);
147 #elif defined(_MSC_VER) && _MSC_VER >= 1200
148 printf("%I64u", *(mat_uint64_t *)data);
149 #elif defined(HAVE_UNSIGNED_LONG_LONG_INT)
150 printf("%llu", (unsigned long long)(*(mat_uint64_t *)data));
151 #else
152 printf("%lu", (unsigned long)(*(mat_uint64_t *)data));
153 #endif
154 break;
155 #endif
156 case MAT_T_INT32:
157 printf("%d", *(mat_int32_t *)data);
158 break;
159 case MAT_T_UINT32:
160 printf("%u", *(mat_uint32_t *)data);
161 break;
162 case MAT_T_INT16:
163 printf("%hd", *(mat_int16_t *)data);
164 break;
165 case MAT_T_UINT16:
166 printf("%hu", *(mat_uint16_t *)data);
167 break;
168 case MAT_T_INT8:
169 printf("%hhd", *(mat_int8_t *)data);
170 break;
171 case MAT_T_UINT8:
172 printf("%hhu", *(mat_uint8_t *)data);
173 break;
174 default:
175 break;
176 }
177 }
178
179 static void
180 Mat_PrintData(int rank, const size_t *_dims, const void *data, enum matio_classes class_type,
181 int isComplex, enum matio_types data_type, size_t nbytes, size_t nelems)
182 {
183 size_t i, j;
184 size_t dims[2];
185
186 assert(NULL != data);
187
188 if ( rank > 2 ) {
189 printf("Can't print more than 2 dimensions\n");
190 return;
191 }
192
193 if ( rank < 1 || NULL == _dims )
194 return;
195
196 if ( 1 == rank ) {
197 // Print as column vector
198 dims[0] = _dims[0];
199 dims[1] = 1;
200 } else {
201 dims[0] = _dims[0];
202 dims[1] = _dims[1];
203 }
204
205 switch ( class_type ) {
206 case MAT_C_DOUBLE:
207 case MAT_C_SINGLE:
208 #ifdef HAVE_MAT_INT64_T
209 case MAT_C_INT64:
210 #endif
211 #ifdef HAVE_MAT_UINT64_T
212 case MAT_C_UINT64:
213 #endif
214 case MAT_C_INT32:
215 case MAT_C_UINT32:
216 case MAT_C_INT16:
217 case MAT_C_UINT16:
218 case MAT_C_INT8:
219 case MAT_C_UINT8: {
220 size_t stride = Mat_SizeOf(data_type);
221 if ( isComplex ) {
222 const mat_complex_split_t *complex_data = (const mat_complex_split_t *)data;
223 const char *rp = (const char *)complex_data->Re;
224 const char *ip = (const char *)complex_data->Im;
225 for ( i = 0; i < dims[0]; i++ ) {
226 for ( j = 0; j < dims[1]; j++ ) {
227 size_t idx = dims[0] * j + i;
228 Mat_PrintNumber(data_type, rp + idx * stride);
229 printf(" + ");
230 Mat_PrintNumber(data_type, ip + idx * stride);
231 printf("i ");
232 }
233 printf("\n");
234 }
235 } else {
236 const char *char_data = (const char *)data;
237 for ( i = 0; i < dims[0]; i++ ) {
238 for ( j = 0; j < dims[1]; j++ ) {
239 size_t idx = dims[0] * j + i;
240 Mat_PrintNumber(data_type, char_data + idx * stride);
241 printf(" ");
242 }
243 printf("\n");
244 }
245 }
246 break;
247 }
248 case MAT_C_CHAR: {
249 switch ( data_type ) {
250 case MAT_T_UINT16:
251 case MAT_T_UTF16: {
252 const mat_uint16_t *uint16_data = (const mat_uint16_t *)data;
253 for ( i = 0; i < dims[0]; i++ ) {
254 for ( j = 0; j < dims[1]; j++ ) {
255 const mat_uint16_t c = uint16_data[j * dims[0] + i];
256 #if defined VARPRINT_UTF16
257 printf("%c%c", c & 0xFF, (c >> 8) & 0xFF);
258 #elif defined VARPRINT_UTF16_DECIMAL
259 Mat_PrintNumber(MAT_T_UINT16, &c);
260 printf(" ");
261 #else
262 /* Convert to UTF-8 */
263 if ( c <= 0x7F ) {
264 printf("%c", c);
265 } else if ( c <= 0x7FF ) {
266 printf("%c%c", 0xC0 | (c >> 6), 0x80 | (c & 0x3F));
267 } else /* if (c <= 0xFFFF) */ {
268 printf("%c%c%c", 0xE0 | (c >> 12), 0x80 | ((c >> 6) & 0x3F),
269 0x80 | (c & 0x3F));
270 }
271 #endif
272 }
273 printf("\n");
274 }
275 break;
276 }
277 case MAT_T_UTF8: {
278 const mat_uint8_t *uint8_data = (const mat_uint8_t *)data;
279 size_t k = 0;
280 int err = 0;
281 size_t *idxOffset;
282 if ( nbytes == 0 ) {
283 break;
284 }
285 idxOffset = (size_t *)calloc(nelems, sizeof(size_t));
286 if ( idxOffset == NULL ) {
287 break;
288 }
289 for ( i = 0; i < dims[0]; i++ ) {
290 if ( err ) {
291 break;
292 }
293 for ( j = 0; j < dims[1]; j++ ) {
294 mat_uint8_t c;
295 if ( k >= nbytes ) {
296 break;
297 }
298 idxOffset[i * dims[1] + j] = k;
299 c = uint8_data[k];
300 if ( c <= 0x7F ) {
301 } else if ( (c & 0xE0) == 0xC0 ) {
302 if ( k + 1 < nbytes ) {
303 k += 1;
304 } else {
305 err = 1;
306 break;
307 }
308 } else if ( (c & 0xF0) == 0xE0 ) {
309 if ( k + 2 < nbytes ) {
310 k += 2;
311 } else {
312 err = 1;
313 break;
314 }
315 } else if ( (c & 0xF8) == 0xF0 ) {
316 if ( k + 3 < nbytes ) {
317 k += 3;
318 } else {
319 err = 1;
320 break;
321 }
322 }
323 ++k;
324 }
325 }
326 if ( err ) {
327 free(idxOffset);
328 Mat_Message("UTF-8 character data error at index %zu", k);
329 break;
330 }
331 for ( i = 0; i < dims[0]; i++ ) {
332 for ( j = 0; j < dims[1]; j++ ) {
333 mat_uint8_t c;
334 k = idxOffset[j * dims[0] + i];
335 c = uint8_data[k];
336 if ( c <= 0x7F ) {
337 printf("%c", c);
338 } else if ( (c & 0xE0) == 0xC0 ) {
339 printf("%c%c", c, uint8_data[k + 1]);
340 } else if ( (c & 0xF0) == 0xE0 ) {
341 printf("%c%c%c", c, uint8_data[k + 1], uint8_data[k + 2]);
342 } else if ( (c & 0xF8) == 0xF0 ) {
343 printf("%c%c%c%c", c, uint8_data[k + 1], uint8_data[k + 2],
344 uint8_data[k + 3]);
345 }
346 }
347 printf("\n");
348 }
349 free(idxOffset);
350 break;
351 }
352 default: {
353 const char *char_data = (const char *)data;
354 for ( i = 0; i < dims[0]; i++ ) {
355 for ( j = 0; j < dims[1]; j++ )
356 printf("%c", char_data[j * dims[0] + i]);
357 printf("\n");
358 }
359 break;
360 }
361 }
362 break;
363 }
364 case MAT_C_SPARSE: {
365 mat_sparse_t *sparse;
366 size_t stride = Mat_SizeOf(data_type);
367 #if !defined(EXTENDED_SPARSE)
368 if ( MAT_T_DOUBLE != data_type )
369 break;
370 #endif
371 sparse = (mat_sparse_t *)data;
372 if ( sparse == NULL || sparse->ndata == 0 || sparse->nir == 0 || sparse->njc == 0 ||
373 sparse->data == NULL ) {
374 break;
375 }
376 if ( isComplex ) {
377 const mat_complex_split_t *complex_data = (const mat_complex_split_t *)sparse->data;
378 const char *re = (const char *)complex_data->Re;
379 const char *im = (const char *)complex_data->Im;
380 for ( i = 0; i < (size_t)sparse->njc - 1; i++ ) {
381 for ( j = sparse->jc[i]; j < (size_t)sparse->jc[i + 1] &&
382 j < (size_t)sparse->ndata && j < (size_t)sparse->nir;
383 j++ ) {
384 printf(" (%u,%" SIZE_T_FMTSTR ") ", sparse->ir[j] + 1, i + 1);
385 Mat_PrintNumber(data_type, re + j * stride);
386 printf(" + ");
387 Mat_PrintNumber(data_type, im + j * stride);
388 printf("i\n");
389 }
390 }
391 } else {
392 const char *sparse_data = (const char *)sparse->data;
393 for ( i = 0; i < (size_t)sparse->njc - 1; i++ ) {
394 for ( j = sparse->jc[i]; j < (size_t)sparse->jc[i + 1] &&
395 j < (size_t)sparse->ndata && j < (size_t)sparse->nir;
396 j++ ) {
397 printf(" (%u,%" SIZE_T_FMTSTR ") ", sparse->ir[j] + 1, i + 1);
398 Mat_PrintNumber(data_type, sparse_data + j * stride);
399 printf("\n");
400 }
401 }
402 }
403 break;
404 }
405 default:
406 break;
407 }
408 }
409
410 mat_complex_split_t *
411 ComplexMalloc(size_t nbytes)
412 {
413 mat_complex_split_t *complex_data = (mat_complex_split_t *)malloc(sizeof(*complex_data));
414 if ( NULL != complex_data ) {
415 complex_data->Re = malloc(nbytes);
416 if ( NULL != complex_data->Re ) {
417 complex_data->Im = malloc(nbytes);
418 if ( NULL == complex_data->Im ) {
419 free(complex_data->Re);
420 free(complex_data);
421 complex_data = NULL;
422 }
423 } else {
424 free(complex_data);
425 complex_data = NULL;
426 }
427 }
428
429 return complex_data;
430 }
431
432 void
433 ComplexFree(mat_complex_split_t *complex_data)
434 {
435 free(complex_data->Re);
436 free(complex_data->Im);
437 free(complex_data);
438 }
439
440 enum matio_types
441 ClassType2DataType(enum matio_classes class_type)
442 {
443 switch ( class_type ) {
444 case MAT_C_DOUBLE:
445 return MAT_T_DOUBLE;
446 case MAT_C_SINGLE:
447 return MAT_T_SINGLE;
448 #ifdef HAVE_MAT_INT64_T
449 case MAT_C_INT64:
450 return MAT_T_INT64;
451 #endif
452 #ifdef HAVE_MAT_UINT64_T
453 case MAT_C_UINT64:
454 return MAT_T_UINT64;
455 #endif
456 case MAT_C_INT32:
457 return MAT_T_INT32;
458 case MAT_C_UINT32:
459 return MAT_T_UINT32;
460 case MAT_C_INT16:
461 return MAT_T_INT16;
462 case MAT_C_UINT16:
463 return MAT_T_UINT16;
464 case MAT_C_INT8:
465 return MAT_T_INT8;
466 case MAT_C_CHAR:
467 return MAT_T_UINT8;
468 case MAT_C_UINT8:
469 return MAT_T_UINT8;
470 case MAT_C_CELL:
471 return MAT_T_CELL;
472 case MAT_C_STRUCT:
473 return MAT_T_STRUCT;
474 default:
475 return MAT_T_UNKNOWN;
476 }
477 }
478
479 /** @brief Gets number of elements from a variable
480 *
481 * Gets number of elements from a variable by overflow-safe
482 * multiplication
483 * @ingroup MAT
484 * @param matvar MAT variable information
485 * @param nelems Number of elements
486 * @retval 0 on success
487 */
488 int
489 Mat_MulDims(const matvar_t *matvar, size_t *nelems)
490 {
491 int i;
492
493 if ( matvar->rank == 0 ) {
494 *nelems = 0;
495 return MATIO_E_NO_ERROR;
496 }
497
498 for ( i = 0; i < matvar->rank; i++ ) {
499 if ( !psnip_safe_size_mul(nelems, *nelems, matvar->dims[i]) ) {
500 *nelems = 0;
501 return MATIO_E_INDEX_TOO_BIG;
502 }
503 }
504
505 return MATIO_E_NO_ERROR;
506 }
507
508 /** @brief Multiplies two unsigned integers
509 *
510 * @param res Result
511 * @param a First operand
512 * @param b Second operand
513 * @retval 0 on success
514 */
515 int
516 Mul(size_t *res, size_t a, size_t b)
517 {
518 if ( !psnip_safe_size_mul(res, a, b) ) {
519 *res = 0;
520 return MATIO_E_INDEX_TOO_BIG;
521 }
522
523 return MATIO_E_NO_ERROR;
524 }
525
526 /** @brief Adds two unsigned integers
527 *
528 * @param res Result
529 * @param a First operand
530 * @param b Second operand
531 * @retval 0 on success
532 */
533 int
534 Add(size_t *res, size_t a, size_t b)
535 {
536 if ( !psnip_safe_size_add(res, a, b) ) {
537 *res = 0;
538 return MATIO_E_INDEX_TOO_BIG;
539 }
540
541 return MATIO_E_NO_ERROR;
542 }
543
544 /** @brief Read from file and check success
545 *
546 * @param buf Buffer for reading
547 * @param size Element size in bytes
548 * @param count Element count
549 * @param fp File pointer
550 * @param[out] bytesread Number of bytes read from the file
551 * @retval 0 on success
552 */
553 int
554 Read(void *buf, size_t size, size_t count, FILE *fp, size_t *bytesread)
555 {
556 const size_t readCount = fread(buf, size, count, fp);
557 int err = readCount != count;
558 if ( NULL != bytesread ) {
559 *bytesread += readCount * size;
560 }
561 if ( err ) {
562 Mat_Warning(
563 "Unexpected end-of-file: Read %zu"
564 " bytes, expected %zu"
565 " bytes",
566 readCount * size, count * size);
567 memset(buf, 0, count * size);
568 }
569 return err;
570 }
571
572 /** @brief Check for End of file
573 *
574 * @param fp File pointer
575 * @param[out] fpos Current file position
576 * @retval 0 on success
577 */
578 int
579 IsEndOfFile(FILE *fp, mat_off_t *fpos)
580 {
581 int isEOF = feof(fp);
582 mat_off_t fPos = ftello(fp);
583 if ( !isEOF ) {
584 if ( fPos == -1L ) {
585 Mat_Critical("Couldn't determine file position");
586 } else {
587 (void)fseeko(fp, 0, SEEK_END);
588 isEOF = fPos == ftello(fp);
589 if ( !isEOF ) {
590 (void)fseeko(fp, fPos, SEEK_SET);
591 }
592 }
593 }
594 if ( NULL != fpos ) {
595 *fpos = fPos;
596 }
597 return isEOF;
598 }
599
600 /** @brief Check for End of file
601 *
602 * @param fp File pointer
603 * @param[out] offset Desired offset from current file position
604 * @retval 0 on success
605 */
606 int
607 CheckSeekFile(FILE *fp, mat_off_t offset)
608 {
609 int err;
610 mat_off_t fPos;
611 uint8_t c;
612
613 if ( offset <= 0 ) {
614 return MATIO_E_NO_ERROR;
615 }
616
617 fPos = ftello(fp);
618 if ( fPos == -1L ) {
619 Mat_Critical("Couldn't determine file position");
620 return MATIO_E_GENERIC_READ_ERROR;
621 }
622
623 (void)fseeko(fp, offset - 1, SEEK_CUR);
624 err = 1 != fread(&c, 1, 1, fp);
625 (void)fseeko(fp, fPos, SEEK_SET);
626 if ( err ) {
627 Mat_Critical("Couldn't set file position");
628 return MATIO_E_GENERIC_READ_ERROR;
629 }
630
631 return MATIO_E_NO_ERROR;
632 }
633
634 /*
635 *===================================================================
636 * Public Functions
637 *===================================================================
638 */
639
640 /** @brief Get the version of the library
641 *
642 * Gets the version number of the library
643 * @param major Pointer to store the library major version number
644 * @param minor Pointer to store the library minor version number
645 * @param release Pointer to store the library release version number
646 */
647 void
648 Mat_GetLibraryVersion(int *major, int *minor, int *release)
649 {
650 if ( NULL != major )
651 *major = MATIO_MAJOR_VERSION;
652 if ( NULL != minor )
653 *minor = MATIO_MINOR_VERSION;
654 if ( NULL != release )
655 *release = MATIO_RELEASE_LEVEL;
656 }
657
658 /** @brief Creates a new Matlab MAT file
659 *
660 * Tries to create a new Matlab MAT file with the given name and optional
661 * header string. If no header string is given, the default string
662 * is used containing the software, version, and date in it. If a header
663 * string is given, at most the first 116 characters is written to the file.
664 * The given header string need not be the full 116 characters, but MUST be
665 * NULL terminated.
666 * @ingroup MAT
667 * @param matname Name of MAT file to create
668 * @param hdr_str Optional header string, NULL to use default
669 * @param mat_file_ver MAT file version to create
670 * @return A pointer to the MAT file or NULL if it failed. This is not a
671 * simple FILE * and should not be used as one.
672 */
673 mat_t *
674 Mat_CreateVer(const char *matname, const char *hdr_str, enum mat_ft mat_file_ver)
675 {
676 mat_t *mat;
677
678 switch ( mat_file_ver ) {
679 case MAT_FT_MAT4:
680 mat = Mat_Create4(matname);
681 break;
682 case MAT_FT_MAT5:
683 mat = Mat_Create5(matname, hdr_str);
684 break;
685 case MAT_FT_MAT73:
686 #if defined(MAT73) && MAT73
687 mat = Mat_Create73(matname, hdr_str);
688 #else
689 mat = NULL;
690 #endif
691 break;
692 default:
693 mat = NULL;
694 break;
695 }
696
697 return mat;
698 }
699
700 /** @brief Opens an existing Matlab MAT file
701 *
702 * Tries to open a Matlab MAT file with the given name
703 * @ingroup MAT
704 * @param matname Name of MAT file to open
705 * @param mode File access mode (MAT_ACC_RDONLY,MAT_ACC_RDWR,etc).
706 * @return A pointer to the MAT file or NULL if it failed. This is not a
707 * simple FILE * and should not be used as one.
708 */
709 mat_t *
710 Mat_Open(const char *matname, int mode)
711 {
712 FILE *fp = NULL;
713 mat_int16_t tmp, tmp2;
714 mat_t *mat = NULL;
715 size_t bytesread = 0;
716
717 if ( (mode & 0x01) == MAT_ACC_RDONLY ) {
718 #if defined(_WIN32)
719 wchar_t *wname = utf82u(matname);
720 if ( NULL != wname ) {
721 fp = _wfopen(wname, L"rb");
722 free(wname);
723 }
724 #else
725 fp = fopen(matname, "rb");
726 #endif
727 if ( !fp ) {
728 Mat_Warning("Cannot open file \"%s\" in read-only mode", matname);
729 return NULL;
730 }
731 } else if ( (mode & 0x01) == MAT_ACC_RDWR ) {
732 #if defined(_WIN32)
733 wchar_t *wname = utf82u(matname);
734 if ( NULL != wname ) {
735 fp = _wfopen(wname, L"r+b");
736 free(wname);
737 }
738 #else
739 fp = fopen(matname, "r+b");
740 #endif
741 if ( !fp ) {
742 mat = Mat_CreateVer(matname, NULL, (enum mat_ft)(mode & 0xfffffffe));
743 return mat;
744 }
745 } else {
746 Mat_Critical("Invalid file open mode");
747 return NULL;
748 }
749
750 mat = (mat_t *)malloc(sizeof(*mat));
751 if ( NULL == mat ) {
752 fclose(fp);
753 Mat_Critical("Couldn't allocate memory for the MAT file");
754 return NULL;
755 }
756
757 mat->fp = fp;
758 mat->header = (char *)calloc(128, sizeof(char));
759 if ( NULL == mat->header ) {
760 free(mat);
761 fclose(fp);
762 Mat_Critical("Couldn't allocate memory for the MAT file header");
763 return NULL;
764 }
765 mat->subsys_offset = (char *)calloc(8, sizeof(char));
766 if ( NULL == mat->subsys_offset ) {
767 free(mat->header);
768 free(mat);
769 fclose(fp);
770 Mat_Critical("Couldn't allocate memory for the MAT file subsys offset");
771 return NULL;
772 }
773 mat->filename = NULL;
774 mat->version = 0;
775 mat->byteswap = 0;
776 mat->num_datasets = 0;
777 #if defined(MAT73) && MAT73
778 mat->refs_id = -1;
779 #endif
780 mat->dir = NULL;
781
782 bytesread += fread(mat->header, 1, 116, fp);
783 mat->header[116] = '\0';
784 bytesread += fread(mat->subsys_offset, 1, 8, fp);
785 bytesread += 2 * fread(&tmp2, 2, 1, fp);
786 bytesread += fread(&tmp, 1, 2, fp);
787
788 if ( 128 == bytesread ) {
789 /* v5 and v7.3 files have at least 128 byte header */
790 mat->byteswap = -1;
791 if ( tmp == 0x4d49 )
792 mat->byteswap = 0;
793 else if ( tmp == 0x494d ) {
794 mat->byteswap = 1;
795 Mat_int16Swap(&tmp2);
796 }
797
798 mat->version = (int)tmp2;
799 if ( (mat->version == 0x0100 || mat->version == 0x0200) && -1 != mat->byteswap ) {
800 mat->bof = ftello((FILE *)mat->fp);
801 if ( mat->bof == -1L ) {
802 free(mat->header);
803 free(mat->subsys_offset);
804 free(mat);
805 fclose(fp);
806 Mat_Critical("Couldn't determine file position");
807 return NULL;
808 }
809 mat->next_index = 0;
810 } else {
811 mat->version = 0;
812 }
813 }
814
815 if ( 0 == mat->version ) {
816 /* Maybe a V4 MAT file */
817 matvar_t *var;
818
819 free(mat->header);
820 free(mat->subsys_offset);
821
822 mat->header = NULL;
823 mat->subsys_offset = NULL;
824 mat->fp = fp;
825 mat->version = MAT_FT_MAT4;
826 mat->byteswap = 0;
827 mat->mode = mode;
828 mat->bof = 0;
829 mat->next_index = 0;
830 #if defined(MAT73) && MAT73
831 mat->refs_id = -1;
832 #endif
833
834 Mat_Rewind(mat);
835 var = Mat_VarReadNextInfo4(mat);
836 if ( NULL == var && bytesread != 0 ) { /* Accept 0 bytes files as a valid V4 file */
837 /* Does not seem to be a valid V4 file */
838 Mat_Close(mat);
839 mat = NULL;
840 Mat_Critical("\"%s\" does not seem to be a valid MAT file", matname);
841 } else {
842 Mat_VarFree(var);
843 Mat_Rewind(mat);
844 }
845 }
846
847 if ( NULL == mat )
848 return mat;
849
850 mat->filename = strdup(matname);
851 mat->mode = mode;
852
853 if ( mat->version == 0x0200 ) {
854 fclose((FILE *)mat->fp);
855 #if defined(MAT73) && MAT73
856 mat->fp = malloc(sizeof(hid_t));
857
858 if ( (mode & 0x01) == MAT_ACC_RDONLY )
859 *(hid_t *)mat->fp = H5Fopen(matname, H5F_ACC_RDONLY, H5P_DEFAULT);
860 else if ( (mode & 0x01) == MAT_ACC_RDWR ) {
861 hid_t plist_ap;
862 plist_ap = H5Pcreate(H5P_FILE_ACCESS);
863 #if H5_VERSION_GE(1, 10, 2)
864 H5Pset_libver_bounds(plist_ap, H5F_LIBVER_EARLIEST, H5F_LIBVER_V18);
865 #endif
866 *(hid_t *)mat->fp = H5Fopen(matname, H5F_ACC_RDWR, plist_ap);
867 H5Pclose(plist_ap);
868 } else {
869 mat->fp = NULL;
870 Mat_Close(mat);
871 mat = NULL;
872 }
873
874 if ( NULL == mat )
875 return mat;
876
877 if ( -1 < *(hid_t *)mat->fp ) {
878 H5G_info_t group_info;
879 herr_t herr;
880 memset(&group_info, 0, sizeof(group_info));
881 herr = H5Gget_info(*(hid_t *)mat->fp, &group_info);
882 if ( herr < 0 ) {
883 Mat_Close(mat);
884 mat = NULL;
885 } else {
886 mat->num_datasets = (size_t)group_info.nlinks;
887 mat->refs_id = H5I_INVALID_HID;
888 }
889 }
890 #else
891 mat->fp = NULL;
892 Mat_Close(mat);
893 mat = NULL;
894 Mat_Critical(
895 "No HDF5 support which is required to read the v7.3 "
896 "MAT file \"%s\"",
897 matname);
898 #endif
899 }
900
901 return mat;
902 }
903
904 /** @brief Closes an open Matlab MAT file
905 *
906 * Closes the given Matlab MAT file and frees any memory with it.
907 * @ingroup MAT
908 * @param mat Pointer to the MAT file
909 * @retval 0 on success
910 */
911 int
912 Mat_Close(mat_t *mat)
913 {
914 int err = MATIO_E_NO_ERROR;
915
916 if ( NULL != mat ) {
917 #if defined(MAT73) && MAT73
918 if ( mat->version == 0x0200 ) {
919 err = Mat_Close73(mat);
920 }
921 #endif
922 if ( NULL != mat->fp ) {
923 err = fclose((FILE *)mat->fp);
924 if ( 0 == err ) {
925 err = MATIO_E_NO_ERROR;
926 } else {
927 err = MATIO_E_FILESYSTEM_ERROR_ON_CLOSE;
928 }
929 }
930 if ( NULL != mat->header )
931 free(mat->header);
932 if ( NULL != mat->subsys_offset )
933 free(mat->subsys_offset);
934 if ( NULL != mat->filename )
935 free(mat->filename);
936 if ( NULL != mat->dir ) {
937 size_t i;
938 for ( i = 0; i < mat->num_datasets; i++ ) {
939 if ( NULL != mat->dir[i] )
940 free(mat->dir[i]);
941 }
942 free(mat->dir);
943 }
944 free(mat);
945 } else {
946 err = MATIO_E_BAD_ARGUMENT;
947 }
948
949 return err;
950 }
951
952 /** @brief Gets the file access mode of the given MAT file
953 *
954 * Gets the file access mode of the given MAT file
955 * @ingroup MAT
956 * @param mat Pointer to the MAT file
957 * @return MAT file access mode
958 */
959 enum mat_acc
960 Mat_GetFileAccessMode(const mat_t *mat)
961 {
962 enum mat_acc mode = MAT_ACC_RDONLY;
963 if ( NULL != mat && (mat->mode & 0x01) == MAT_ACC_RDWR )
964 mode = MAT_ACC_RDWR;
965 return mode;
966 }
967
968 /** @brief Gets the filename for the given MAT file
969 *
970 * Gets the filename for the given MAT file
971 * @ingroup MAT
972 * @param mat Pointer to the MAT file
973 * @return MAT filename
974 */
975 const char *
976 Mat_GetFilename(const mat_t *mat)
977 {
978 const char *filename = NULL;
979 if ( NULL != mat )
980 filename = mat->filename;
981 return filename;
982 }
983
984 /** @brief Gets the header for the given MAT file
985 *
986 * Gets the header for the given MAT file
987 * @ingroup MAT
988 * @param mat Pointer to the MAT file
989 * @return MAT header
990 */
991 const char *
992 Mat_GetHeader(const mat_t *mat)
993 {
994 const char *header = NULL;
995 if ( NULL != mat )
996 header = mat->header;
997 return header;
998 }
999
1000 /** @brief Gets the version of the given MAT file
1001 *
1002 * Gets the version of the given MAT file
1003 * @ingroup MAT
1004 * @param mat Pointer to the MAT file
1005 * @return MAT file version
1006 */
1007 enum mat_ft
1008 Mat_GetVersion(const mat_t *mat)
1009 {
1010 enum mat_ft file_type = MAT_FT_UNDEFINED;
1011 if ( NULL != mat )
1012 file_type = (enum mat_ft)mat->version;
1013 return file_type;
1014 }
1015
1016 /** @brief Gets a list of the variables of a MAT file
1017 *
1018 * Gets a list of the variables of a MAT file
1019 * @ingroup MAT
1020 * @param mat Pointer to the MAT file
1021 * @param[out] n Number of variables in the given MAT file
1022 * @return Array of variable names
1023 */
1024 char *const *
1025 Mat_GetDir(mat_t *mat, size_t *n)
1026 {
1027 char **dir = NULL;
1028
1029 if ( NULL == n )
1030 return dir;
1031
1032 if ( NULL == mat ) {
1033 *n = 0;
1034 return dir;
1035 }
1036
1037 if ( NULL == mat->dir ) {
1038 if ( mat->version == MAT_FT_MAT73 ) {
1039 #if defined(MAT73) && MAT73
1040 int err = Mat_CalcDir73(mat, n);
1041 if ( err ) {
1042 *n = 0;
1043 return dir;
1044 }
1045 #else
1046 *n = 0;
1047 #endif
1048 } else {
1049 matvar_t *matvar = NULL;
1050 mat_off_t fpos = ftello((FILE *)mat->fp);
1051 if ( fpos == -1L ) {
1052 *n = 0;
1053 Mat_Critical("Couldn't determine file position");
1054 return dir;
1055 }
1056 (void)fseeko((FILE *)mat->fp, mat->bof, SEEK_SET);
1057 mat->num_datasets = 0;
1058 do {
1059 matvar = Mat_VarReadNextInfo(mat);
1060 if ( NULL != matvar ) {
1061 if ( NULL != matvar->name ) {
1062 if ( NULL == mat->dir ) {
1063 dir = (char **)malloc(sizeof(char *));
1064 } else {
1065 dir = (char **)realloc(mat->dir,
1066 (mat->num_datasets + 1) * (sizeof(char *)));
1067 }
1068 if ( NULL != dir ) {
1069 mat->dir = dir;
1070 mat->dir[mat->num_datasets++] = strdup(matvar->name);
1071 } else {
1072 Mat_Critical("Couldn't allocate memory for the directory");
1073 break;
1074 }
1075 }
1076 Mat_VarFree(matvar);
1077 } else if ( !IsEndOfFile((FILE *)mat->fp, NULL) ) {
1078 Mat_Critical("An error occurred in reading the MAT file");
1079 break;
1080 }
1081 } while ( !IsEndOfFile((FILE *)mat->fp, NULL) );
1082 (void)fseeko((FILE *)mat->fp, fpos, SEEK_SET);
1083 *n = mat->num_datasets;
1084 }
1085 } else {
1086 if ( mat->version == MAT_FT_MAT73 ) {
1087 *n = 0;
1088 while ( *n < mat->num_datasets && NULL != mat->dir[*n] ) {
1089 (*n)++;
1090 }
1091 } else {
1092 *n = mat->num_datasets;
1093 }
1094 }
1095 dir = mat->dir;
1096 return dir;
1097 }
1098
1099 /** @brief Rewinds a Matlab MAT file to the first variable
1100 *
1101 * Rewinds a Matlab MAT file to the first variable
1102 * @ingroup MAT
1103 * @param mat Pointer to the MAT file
1104 * @retval 0 on success
1105 */
1106 int
1107 Mat_Rewind(mat_t *mat)
1108 {
1109 int err = MATIO_E_NO_ERROR;
1110
1111 switch ( mat->version ) {
1112 case MAT_FT_MAT73:
1113 mat->next_index = 0;
1114 break;
1115 case MAT_FT_MAT4:
1116 case MAT_FT_MAT5:
1117 (void)fseeko((FILE *)mat->fp, mat->bof, SEEK_SET);
1118 break;
1119 default:
1120 err = MATIO_E_FAIL_TO_IDENTIFY;
1121 break;
1122 }
1123
1124 return err;
1125 }
1126
1127 /** @brief Returns the size of a Matlab Class
1128 *
1129 * Returns the size (in bytes) of the matlab class class_type
1130 * @ingroup MAT
1131 * @param class_type Matlab class type (MAT_C_*)
1132 * @returns Size of the class
1133 */
1134 size_t
1135 Mat_SizeOfClass(int class_type)
1136 {
1137 switch ( class_type ) {
1138 case MAT_C_DOUBLE:
1139 return sizeof(double);
1140 case MAT_C_SINGLE:
1141 return sizeof(float);
1142 #ifdef HAVE_MAT_INT64_T
1143 case MAT_C_INT64:
1144 return sizeof(mat_int64_t);
1145 #endif
1146 #ifdef HAVE_MAT_UINT64_T
1147 case MAT_C_UINT64:
1148 return sizeof(mat_uint64_t);
1149 #endif
1150 case MAT_C_INT32:
1151 return sizeof(mat_int32_t);
1152 case MAT_C_UINT32:
1153 return sizeof(mat_uint32_t);
1154 case MAT_C_INT16:
1155 return sizeof(mat_int16_t);
1156 case MAT_C_UINT16:
1157 return sizeof(mat_uint16_t);
1158 case MAT_C_INT8:
1159 return sizeof(mat_int8_t);
1160 case MAT_C_UINT8:
1161 return sizeof(mat_uint8_t);
1162 case MAT_C_CHAR:
1163 return sizeof(mat_int16_t);
1164 default:
1165 return 0;
1166 }
1167 }
1168
1169 /*
1170 *===================================================================
1171 * MAT Variable Functions
1172 *===================================================================
1173 */
1174
1175 /** @brief Allocates memory for a new matvar_t and initializes all the fields
1176 *
1177 * @ingroup MAT
1178 * @return A newly allocated matvar_t
1179 */
1180 matvar_t *
1181 Mat_VarCalloc(void)
1182 {
1183 matvar_t *matvar;
1184
1185 matvar = (matvar_t *)malloc(sizeof(*matvar));
1186
1187 if ( NULL != matvar ) {
1188 matvar->nbytes = 0;
1189 matvar->rank = 0;
1190 matvar->data_type = MAT_T_UNKNOWN;
1191 matvar->data_size = 0;
1192 matvar->class_type = MAT_C_EMPTY;
1193 matvar->isComplex = 0;
1194 matvar->isGlobal = 0;
1195 matvar->isLogical = 0;
1196 matvar->dims = NULL;
1197 matvar->name = NULL;
1198 matvar->data = NULL;
1199 matvar->mem_conserve = 0;
1200 matvar->compression = MAT_COMPRESSION_NONE;
1201 matvar->internal = (struct matvar_internal *)malloc(sizeof(*matvar->internal));
1202 if ( NULL == matvar->internal ) {
1203 free(matvar);
1204 matvar = NULL;
1205 } else {
1206 #if defined(MAT73) && MAT73
1207 matvar->internal->hdf5_ref = 0;
1208 matvar->internal->id = H5I_INVALID_HID;
1209 #endif
1210 matvar->internal->datapos = 0;
1211 matvar->internal->num_fields = 0;
1212 matvar->internal->fieldnames = NULL;
1213 #if HAVE_ZLIB
1214 matvar->internal->z = NULL;
1215 matvar->internal->data = NULL;
1216 #endif
1217 }
1218 }
1219
1220 return matvar;
1221 }
1222
1223 /** @brief Creates a MAT Variable with the given name and (optionally) data
1224 *
1225 * Creates a MAT variable that can be written to a Matlab MAT file with the
1226 * given name, data type, dimensions and data. Rank should always be 2 or more.
1227 * i.e. Scalar values would have rank=2 and dims[2] = {1,1}. Data type is
1228 * one of the MAT_T types. MAT adds MAT_T_STRUCT and MAT_T_CELL to create
1229 * Structures and Cell Arrays respectively. For MAT_T_STRUCT, data should be a
1230 * NULL terminated array of matvar_t * variables (i.e. for a 3x2 structure with
1231 * 10 fields, there should be 61 matvar_t * variables where the last one is
1232 * NULL). For cell arrays, the NULL termination isn't necessary. So to create
1233 * a cell array of size 3x2, data would be the address of an array of 6
1234 * matvar_t * variables.
1235 *
1236 * EXAMPLE:
1237 * To create a struct of size 3x2 with 3 fields:
1238 * @code
1239 * int rank=2, dims[2] = {3,2}, nfields = 3;
1240 * matvar_t **vars;
1241 *
1242 * vars = malloc((3*2*nfields+1)*sizeof(matvar_t *));
1243 * vars[0] = Mat_VarCreate(...);
1244 * :
1245 * vars[3*2*nfields-1] = Mat_VarCreate(...);
1246 * vars[3*2*nfields] = NULL;
1247 * @endcode
1248 *
1249 * EXAMPLE:
1250 * To create a cell array of size 3x2:
1251 * @code
1252 * int rank=2, dims[2] = {3,2};
1253 * matvar_t **vars;
1254 *
1255 * vars = malloc(3*2*sizeof(matvar_t *));
1256 * vars[0] = Mat_VarCreate(...);
1257 * :
1258 * vars[5] = Mat_VarCreate(...);
1259 * @endcode
1260 *
1261 * @ingroup MAT
1262 * @param name Name of the variable to create
1263 * @param class_type class type of the variable in Matlab(one of the mx Classes)
1264 * @param data_type data type of the variable (one of the MAT_T_ Types)
1265 * @param rank Rank of the variable
1266 * @param dims array of dimensions of the variable of size rank
1267 * @param data pointer to the data
1268 * @param opt 0, or bitwise or of the following options:
1269 * - MAT_F_DONT_COPY_DATA to just use the pointer to the data and not copy the
1270 * data itself. Note that the pointer should not be freed until you are
1271 * done with the mat variable. The Mat_VarFree function will NOT free
1272 * data that was created with MAT_F_DONT_COPY_DATA, so free it yourself.
1273 * - MAT_F_COMPLEX to specify that the data is complex. The data variable
1274 * should be a pointer to a mat_complex_split_t type.
1275 * - MAT_F_GLOBAL to assign the variable as a global variable
1276 * - MAT_F_LOGICAL to specify that it is a logical variable
1277 * @return A MAT variable that can be written to a file or otherwise used
1278 */
1279 matvar_t *
1280 Mat_VarCreate(const char *name, enum matio_classes class_type, enum matio_types data_type, int rank,
1281 const size_t *dims, const void *data, int opt)
1282 {
1283 size_t nelems = 1, data_size;
1284 matvar_t *matvar = NULL;
1285 int j, err;
1286
1287 if ( dims == NULL )
1288 return NULL;
1289
1290 matvar = Mat_VarCalloc();
1291 if ( NULL == matvar )
1292 return NULL;
1293
1294 matvar->compression = MAT_COMPRESSION_NONE;
1295 matvar->isComplex = opt & MAT_F_COMPLEX;
1296 matvar->isGlobal = opt & MAT_F_GLOBAL;
1297 matvar->isLogical = opt & MAT_F_LOGICAL;
1298 if ( name )
1299 matvar->name = strdup(name);
1300 matvar->rank = rank;
1301 matvar->dims = (size_t *)malloc(matvar->rank * sizeof(*matvar->dims));
1302 for ( j = 0; j < matvar->rank; j++ ) {
1303 matvar->dims[j] = dims[j];
1304 nelems *= dims[j];
1305 }
1306 matvar->class_type = class_type;
1307 matvar->data_type = data_type;
1308 switch ( data_type ) {
1309 case MAT_T_INT8:
1310 data_size = 1;
1311 break;
1312 case MAT_T_UINT8:
1313 data_size = 1;
1314 break;
1315 case MAT_T_INT16:
1316 data_size = 2;
1317 break;
1318 case MAT_T_UINT16:
1319 data_size = 2;
1320 break;
1321 case MAT_T_INT64:
1322 data_size = 8;
1323 break;
1324 case MAT_T_UINT64:
1325 data_size = 8;
1326 break;
1327 case MAT_T_INT32:
1328 data_size = 4;
1329 break;
1330 case MAT_T_UINT32:
1331 data_size = 4;
1332 break;
1333 case MAT_T_SINGLE:
1334 data_size = sizeof(float);
1335 break;
1336 case MAT_T_DOUBLE:
1337 data_size = sizeof(double);
1338 break;
1339 case MAT_T_UTF8:
1340 data_size = 1;
1341 break;
1342 case MAT_T_UTF16:
1343 data_size = 2;
1344 break;
1345 case MAT_T_UTF32:
1346 data_size = 4;
1347 break;
1348 case MAT_T_CELL:
1349 data_size = sizeof(matvar_t **);
1350 break;
1351 case MAT_T_STRUCT: {
1352 data_size = sizeof(matvar_t **);
1353 if ( data != NULL ) {
1354 matvar_t *const *const fields = (matvar_t *const *const)data;
1355 size_t nfields = 0;
1356 while ( fields[nfields] != NULL )
1357 nfields++;
1358 if ( nelems )
1359 nfields /= nelems;
1360 matvar->internal->num_fields = nfields;
1361 if ( nfields ) {
1362 size_t i;
1363 matvar->internal->fieldnames =
1364 (char **)calloc(nfields, sizeof(*matvar->internal->fieldnames));
1365 for ( i = 0; i < nfields; i++ )
1366 matvar->internal->fieldnames[i] = strdup(fields[i]->name);
1367 err = Mul(&nelems, nelems, nfields);
1368 if ( err ) {
1369 Mat_VarFree(matvar);
1370 Mat_Critical("Integer multiplication overflow");
1371 return NULL;
1372 }
1373 }
1374 }
1375 break;
1376 }
1377 default:
1378 Mat_VarFree(matvar);
1379 Mat_Critical("Unrecognized data_type");
1380 return NULL;
1381 }
1382 if ( matvar->class_type == MAT_C_SPARSE ) {
1383 matvar->data_size = sizeof(mat_sparse_t);
1384 matvar->nbytes = matvar->data_size;
1385 } else if ( matvar->class_type == MAT_C_CHAR && matvar->data_type == MAT_T_UTF8 ) {
1386 size_t k = 0;
1387 if ( data != NULL ) {
1388 size_t i;
1389 const mat_uint8_t *ptr = (const mat_uint8_t *)data;
1390 for ( i = 0; i < nelems; i++ ) {
1391 const mat_uint8_t c = ptr[k];
1392 if ( c <= 0x7F ) {
1393 k++;
1394 } else if ( (c & 0xE0) == 0xC0 ) {
1395 k += 2;
1396 } else if ( (c & 0xF0) == 0xE0 ) {
1397 k += 3;
1398 } else if ( (c & 0xF8) == 0xF0 ) {
1399 k += 4;
1400 }
1401 }
1402 }
1403 matvar->nbytes = k;
1404 matvar->data_size = (int)data_size;
1405 } else {
1406 matvar->data_size = (int)data_size;
1407 err = Mul(&matvar->nbytes, nelems, matvar->data_size);
1408 if ( err ) {
1409 Mat_VarFree(matvar);
1410 Mat_Critical("Integer multiplication overflow");
1411 return NULL;
1412 }
1413 }
1414 if ( data == NULL ) {
1415 if ( MAT_C_CELL == matvar->class_type && nelems > 0 )
1416 matvar->data = calloc(nelems, sizeof(matvar_t *));
1417 } else if ( opt & MAT_F_DONT_COPY_DATA ) {
1418 matvar->data = (void *)data;
1419 matvar->mem_conserve = 1;
1420 } else if ( MAT_C_SPARSE == matvar->class_type ) {
1421 const mat_sparse_t *sparse_data_in = (const mat_sparse_t *)data;
1422 mat_sparse_t *sparse_data = (mat_sparse_t *)malloc(sizeof(mat_sparse_t));
1423 if ( NULL != sparse_data ) {
1424 sparse_data->nzmax = sparse_data_in->nzmax;
1425 sparse_data->nir = sparse_data_in->nir;
1426 sparse_data->njc = sparse_data_in->njc;
1427 sparse_data->ndata = sparse_data_in->ndata;
1428 if ( NULL != sparse_data_in->ir ) {
1429 sparse_data->ir =
1430 (mat_uint32_t *)malloc(sparse_data->nir * sizeof(*sparse_data->ir));
1431 if ( NULL != sparse_data->ir )
1432 memcpy(sparse_data->ir, sparse_data_in->ir,
1433 sparse_data->nir * sizeof(*sparse_data->ir));
1434 } else {
1435 sparse_data->ir = NULL;
1436 }
1437 if ( NULL != sparse_data_in->jc ) {
1438 sparse_data->jc =
1439 (mat_uint32_t *)malloc(sparse_data->njc * sizeof(*sparse_data->jc));
1440 if ( NULL != sparse_data->jc )
1441 memcpy(sparse_data->jc, sparse_data_in->jc,
1442 sparse_data->njc * sizeof(*sparse_data->jc));
1443 } else {
1444 sparse_data->jc = NULL;
1445 }
1446 if ( NULL != sparse_data_in->data ) {
1447 if ( matvar->isComplex ) {
1448 sparse_data->data = malloc(sizeof(mat_complex_split_t));
1449 if ( NULL != sparse_data->data ) {
1450 mat_complex_split_t *complex_data =
1451 (mat_complex_split_t *)sparse_data->data;
1452 const mat_complex_split_t *complex_data_in =
1453 (mat_complex_split_t *)sparse_data_in->data;
1454 complex_data->Re = malloc(sparse_data->ndata * data_size);
1455 complex_data->Im = malloc(sparse_data->ndata * data_size);
1456 if ( NULL != complex_data->Re )
1457 memcpy(complex_data->Re, complex_data_in->Re,
1458 sparse_data->ndata * data_size);
1459 if ( NULL != complex_data->Im )
1460 memcpy(complex_data->Im, complex_data_in->Im,
1461 sparse_data->ndata * data_size);
1462 }
1463 } else {
1464 sparse_data->data = malloc(sparse_data->ndata * data_size);
1465 if ( NULL != sparse_data->data )
1466 memcpy(sparse_data->data, sparse_data_in->data,
1467 sparse_data->ndata * data_size);
1468 }
1469 } else {
1470 sparse_data->data = NULL;
1471 }
1472 }
1473 matvar->data = sparse_data;
1474 } else {
1475 if ( matvar->isComplex ) {
1476 matvar->data = malloc(sizeof(mat_complex_split_t));
1477 if ( NULL != matvar->data && matvar->nbytes > 0 ) {
1478 mat_complex_split_t *complex_data = (mat_complex_split_t *)matvar->data;
1479 const mat_complex_split_t *complex_data_in = (const mat_complex_split_t *)data;
1480
1481 complex_data->Re = malloc(matvar->nbytes);
1482 complex_data->Im = malloc(matvar->nbytes);
1483 if ( NULL != complex_data->Re )
1484 memcpy(complex_data->Re, complex_data_in->Re, matvar->nbytes);
1485 if ( NULL != complex_data->Im )
1486 memcpy(complex_data->Im, complex_data_in->Im, matvar->nbytes);
1487 }
1488 } else if ( matvar->nbytes > 0 ) {
1489 matvar->data = malloc(matvar->nbytes);
1490 if ( NULL != matvar->data )
1491 memcpy(matvar->data, data, matvar->nbytes);
1492 }
1493 matvar->mem_conserve = 0;
1494 }
1495
1496 return matvar;
1497 }
1498
1499 /** @brief Copies a file
1500 *
1501 * @param src source file path
1502 * @param dst destination file path
1503 * @retval 0 on success
1504 */
1505 static int
1506 Mat_CopyFile(const char *src, const char *dst)
1507 {
1508 size_t len;
1509 char buf[BUFSIZ] = {'\0'};
1510 FILE *in;
1511 FILE *out = NULL;
1512
1513 #if defined(_WIN32)
1514 {
1515 wchar_t *wname = utf82u(src);
1516 if ( NULL != wname ) {
1517 in = _wfopen(wname, L"rb");
1518 free(wname);
1519 } else {
1520 in = NULL;
1521 }
1522 }
1523 #else
1524 in = fopen(src, "rb");
1525 #endif
1526 if ( in == NULL ) {
1527 Mat_Critical("Cannot open file \"%s\" for reading", src);
1528 return MATIO_E_FILESYSTEM_COULD_NOT_OPEN;
1529 }
1530
1531 #if defined(_WIN32)
1532 {
1533 wchar_t *wname = utf82u(dst);
1534 if ( NULL != wname ) {
1535 out = _wfopen(wname, L"wb");
1536 free(wname);
1537 }
1538 }
1539 #else
1540 out = fopen(dst, "wb");
1541 #endif
1542 if ( out == NULL ) {
1543 fclose(in);
1544 Mat_Critical("Cannot open file \"%s\" for writing", dst);
1545 return MATIO_E_FILESYSTEM_COULD_NOT_OPEN;
1546 }
1547
1548 while ( (len = fread(buf, sizeof(char), BUFSIZ, in)) > 0 ) {
1549 if ( len != fwrite(buf, sizeof(char), len, out) ) {
1550 fclose(in);
1551 fclose(out);
1552 Mat_Critical("Error writing to file \"%s\"", dst);
1553 return MATIO_E_GENERIC_WRITE_ERROR;
1554 }
1555 }
1556 fclose(in);
1557 fclose(out);
1558 return MATIO_E_NO_ERROR;
1559 }
1560
1561 /** @brief Deletes a variable from a file
1562 *
1563 * @ingroup MAT
1564 * @param mat Pointer to the mat_t file structure
1565 * @param name Name of the variable to delete
1566 * @returns 0 on success
1567 */
1568 int
1569 Mat_VarDelete(mat_t *mat, const char *name)
1570 {
1571 int err = MATIO_E_BAD_ARGUMENT;
1572 char path_buf[MAT_MKTEMP_BUF_SIZE];
1573 char dir_buf[MAT_MKTEMP_BUF_SIZE];
1574
1575 if ( NULL == mat || NULL == name )
1576 return err;
1577
1578 if ( (mat->mode & 0x01) == MAT_ACC_RDONLY )
1579 return MATIO_E_OPERATION_PROHIBITED_IN_READ_MODE;
1580
1581 if ( NULL != Mat_mktemp(path_buf, dir_buf) ) {
1582 enum mat_ft mat_file_ver;
1583 mat_t *tmp;
1584
1585 switch ( mat->version ) {
1586 case 0x0100:
1587 mat_file_ver = MAT_FT_MAT5;
1588 break;
1589 case 0x0200:
1590 mat_file_ver = MAT_FT_MAT73;
1591 break;
1592 case 0x0010:
1593 mat_file_ver = MAT_FT_MAT4;
1594 break;
1595 default:
1596 mat_file_ver = MAT_FT_DEFAULT;
1597 break;
1598 }
1599
1600 tmp = Mat_CreateVer(path_buf, mat->header, mat_file_ver);
1601 if ( tmp != NULL ) {
1602 matvar_t *matvar;
1603 char **dir;
1604 size_t n;
1605
1606 Mat_Rewind(mat);
1607 while ( NULL != (matvar = Mat_VarReadNext(mat)) ) {
1608 if ( 0 != strcmp(matvar->name, name) )
1609 err = Mat_VarWrite(tmp, matvar, matvar->compression);
1610 else
1611 err = MATIO_E_NO_ERROR;
1612 Mat_VarFree(matvar);
1613 }
1614 dir = tmp->dir; /* Keep directory for later assignment */
1615 tmp->dir = NULL;
1616 n = tmp->num_datasets;
1617 Mat_Close(tmp);
1618
1619 if ( MATIO_E_NO_ERROR == err ) {
1620 char *new_name = strdup(mat->filename);
1621 #if defined(MAT73) && MAT73
1622 if ( mat_file_ver == MAT_FT_MAT73 ) {
1623 /* err = */ Mat_Close73(mat);
1624 }
1625 #endif
1626 if ( mat->fp != NULL ) {
1627 fclose((FILE *)mat->fp);
1628 mat->fp = NULL;
1629 }
1630
1631 if ( (err = Mat_CopyFile(path_buf, new_name)) != MATIO_E_NO_ERROR ) {
1632 if ( NULL != dir ) {
1633 size_t i;
1634 for ( i = 0; i < n; i++ ) {
1635 if ( dir[i] )
1636 free(dir[i]);
1637 }
1638 free(dir);
1639 }
1640 Mat_Critical("Cannot copy file from \"%s\" to \"%s\"", path_buf, new_name);
1641 } else if ( (err = remove(path_buf)) != 0 ) {
1642 err = MATIO_E_UNKNOWN_ERROR;
1643 if ( NULL != dir ) {
1644 size_t i;
1645 for ( i = 0; i < n; i++ ) {
1646 if ( dir[i] )
1647 free(dir[i]);
1648 }
1649 free(dir);
1650 }
1651 Mat_Critical("Cannot remove file \"%s\"", path_buf);
1652 } else if ( *dir_buf != '\0' && (err = remove(dir_buf)) != 0 ) {
1653 err = MATIO_E_UNKNOWN_ERROR;
1654 if ( NULL != dir ) {
1655 size_t i;
1656 for ( i = 0; i < n; i++ ) {
1657 if ( dir[i] )
1658 free(dir[i]);
1659 }
1660 free(dir);
1661 }
1662 Mat_Critical("Cannot remove directory \"%s\"", dir_buf);
1663 } else {
1664 tmp = Mat_Open(new_name, mat->mode);
1665 if ( NULL != tmp ) {
1666 if ( mat->header )
1667 free(mat->header);
1668 if ( mat->subsys_offset )
1669 free(mat->subsys_offset);
1670 if ( mat->filename )
1671 free(mat->filename);
1672 if ( mat->dir ) {
1673 size_t i;
1674 for ( i = 0; i < mat->num_datasets; i++ ) {
1675 if ( mat->dir[i] )
1676 free(mat->dir[i]);
1677 }
1678 free(mat->dir);
1679 }
1680 memcpy(mat, tmp, sizeof(mat_t));
1681 free(tmp);
1682 mat->num_datasets = n;
1683 mat->dir = dir;
1684 } else {
1685 Mat_Critical("Cannot open file \"%s\"", new_name);
1686 err = MATIO_E_FILESYSTEM_COULD_NOT_OPEN;
1687 }
1688 }
1689 free(new_name);
1690 } else if ( (err = remove(path_buf)) != 0 ) {
1691 err = MATIO_E_UNKNOWN_ERROR;
1692 Mat_Critical("Cannot remove file \"%s\"", path_buf);
1693 } else if ( *dir_buf != '\0' && (err = remove(dir_buf)) != 0 ) {
1694 err = MATIO_E_UNKNOWN_ERROR;
1695 Mat_Critical("Cannot remove directory \"%s\"", dir_buf);
1696 }
1697 } else {
1698 err = MATIO_E_UNKNOWN_ERROR;
1699 }
1700 } else {
1701 Mat_Critical("Cannot create a unique file name");
1702 err = MATIO_E_FILESYSTEM_COULD_NOT_OPEN_TEMPORARY;
1703 }
1704
1705 return err;
1706 }
1707
1708 /** @brief Duplicates a matvar_t structure
1709 *
1710 * Provides a clean function for duplicating a matvar_t structure.
1711 * @ingroup MAT
1712 * @param in pointer to the matvar_t structure to be duplicated
1713 * @param opt 0 does a shallow duplicate and only assigns the data pointer to
1714 * the duplicated array. 1 will do a deep duplicate and actually
1715 * duplicate the contents of the data. Warning: If you do a shallow
1716 * copy and free both structures, the data will be freed twice and
1717 * memory will be corrupted. This may be fixed in a later release.
1718 * @returns Pointer to the duplicated matvar_t structure.
1719 */
1720 matvar_t *
1721 Mat_VarDuplicate(const matvar_t *in, int opt)
1722 {
1723 matvar_t *out;
1724 size_t i;
1725
1726 if ( in == NULL )
1727 return NULL;
1728
1729 out = Mat_VarCalloc();
1730 if ( out == NULL )
1731 return NULL;
1732
1733 out->nbytes = in->nbytes;
1734 out->rank = in->rank;
1735 out->data_type = in->data_type;
1736 out->data_size = in->data_size;
1737 out->class_type = in->class_type;
1738 out->isComplex = in->isComplex;
1739 out->isGlobal = in->isGlobal;
1740 out->isLogical = in->isLogical;
1741 out->mem_conserve = in->mem_conserve;
1742 out->compression = in->compression;
1743
1744 if ( NULL != in->name ) {
1745 size_t len = strlen(in->name) + 1;
1746 out->name = (char *)malloc(len);
1747 if ( NULL != out->name )
1748 memcpy(out->name, in->name, len);
1749 }
1750
1751 out->dims = (size_t *)malloc(in->rank * sizeof(*out->dims));
1752 if ( out->dims != NULL )
1753 memcpy(out->dims, in->dims, in->rank * sizeof(*out->dims));
1754
1755 if ( NULL != in->internal ) {
1756 #if defined(MAT73) && MAT73
1757 out->internal->hdf5_ref = in->internal->hdf5_ref;
1758 out->internal->id = in->internal->id;
1759 if ( out->internal->id >= 0 ) {
1760 H5Iinc_ref(out->internal->id);
1761 }
1762 #endif
1763 out->internal->datapos = in->internal->datapos;
1764 #if HAVE_ZLIB
1765 out->internal->z = NULL;
1766 out->internal->data = NULL;
1767 #endif
1768 out->internal->num_fields = in->internal->num_fields;
1769 if ( NULL != in->internal->fieldnames && in->internal->num_fields > 0 ) {
1770 out->internal->fieldnames =
1771 (char **)calloc(in->internal->num_fields, sizeof(*in->internal->fieldnames));
1772 if ( NULL != out->internal->fieldnames ) {
1773 for ( i = 0; i < in->internal->num_fields; i++ ) {
1774 if ( NULL != in->internal->fieldnames[i] )
1775 out->internal->fieldnames[i] = strdup(in->internal->fieldnames[i]);
1776 }
1777 }
1778 }
1779
1780 #if HAVE_ZLIB
1781 if ( in->internal->z != NULL ) {
1782 out->internal->z = (z_streamp)malloc(sizeof(z_stream));
1783 if ( NULL != out->internal->z ) {
1784 int err = inflateCopy(out->internal->z, in->internal->z);
1785 if ( err != Z_OK ) {
1786 free(out->internal->z);
1787 out->internal->z = NULL;
1788 }
1789 }
1790 }
1791 if ( in->internal->data != NULL ) {
1792 if ( in->class_type == MAT_C_SPARSE ) {
1793 out->internal->data = malloc(sizeof(mat_sparse_t));
1794 if ( out->internal->data != NULL ) {
1795 mat_sparse_t *out_sparse = (mat_sparse_t *)out->internal->data;
1796 mat_sparse_t *in_sparse = (mat_sparse_t *)in->internal->data;
1797 out_sparse->nzmax = in_sparse->nzmax;
1798 out_sparse->nir = in_sparse->nir;
1799 out_sparse->ir =
1800 (mat_uint32_t *)malloc(in_sparse->nir * sizeof(*out_sparse->ir));
1801 if ( out_sparse->ir != NULL )
1802 memcpy(out_sparse->ir, in_sparse->ir,
1803 in_sparse->nir * sizeof(*out_sparse->ir));
1804 out_sparse->njc = in_sparse->njc;
1805 out_sparse->jc =
1806 (mat_uint32_t *)malloc(in_sparse->njc * sizeof(*out_sparse->jc));
1807 if ( out_sparse->jc != NULL )
1808 memcpy(out_sparse->jc, in_sparse->jc,
1809 in_sparse->njc * sizeof(*out_sparse->jc));
1810 out_sparse->ndata = in_sparse->ndata;
1811 if ( out->isComplex && NULL != in_sparse->data ) {
1812 out_sparse->data = malloc(sizeof(mat_complex_split_t));
1813 if ( out_sparse->data != NULL ) {
1814 mat_complex_split_t *out_data = (mat_complex_split_t *)out_sparse->data;
1815 const mat_complex_split_t *in_data =
1816 (mat_complex_split_t *)in_sparse->data;
1817 out_data->Re = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1818 if ( NULL != out_data->Re )
1819 memcpy(out_data->Re, in_data->Re,
1820 in_sparse->ndata * Mat_SizeOf(in->data_type));
1821 out_data->Im = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1822 if ( NULL != out_data->Im )
1823 memcpy(out_data->Im, in_data->Im,
1824 in_sparse->ndata * Mat_SizeOf(in->data_type));
1825 }
1826 } else if ( in_sparse->data != NULL ) {
1827 out_sparse->data = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1828 if ( NULL != out_sparse->data )
1829 memcpy(out_sparse->data, in_sparse->data,
1830 in_sparse->ndata * Mat_SizeOf(in->data_type));
1831 } else {
1832 out_sparse->data = NULL;
1833 }
1834 }
1835 } else if ( out->isComplex ) {
1836 out->internal->data = malloc(sizeof(mat_complex_split_t));
1837 if ( out->internal->data != NULL ) {
1838 mat_complex_split_t *out_data = (mat_complex_split_t *)out->internal->data;
1839 const mat_complex_split_t *in_data = (mat_complex_split_t *)in->internal->data;
1840 out_data->Re = malloc(out->nbytes);
1841 if ( NULL != out_data->Re )
1842 memcpy(out_data->Re, in_data->Re, out->nbytes);
1843 out_data->Im = malloc(out->nbytes);
1844 if ( NULL != out_data->Im )
1845 memcpy(out_data->Im, in_data->Im, out->nbytes);
1846 }
1847 } else if ( NULL != (out->internal->data = malloc(in->nbytes)) ) {
1848 memcpy(out->internal->data, in->internal->data, in->nbytes);
1849 }
1850 }
1851 #endif
1852 } else {
1853 free(out->internal);
1854 out->internal = NULL;
1855 }
1856
1857 if ( !opt ) {
1858 out->data = in->data;
1859 } else if ( in->data != NULL &&
1860 (in->class_type == MAT_C_STRUCT || in->class_type == MAT_C_CELL ||
1861 in->class_type == MAT_C_FUNCTION) ) {
1862 out->data = malloc(in->nbytes);
1863 if ( out->data != NULL && in->data_size > 0 ) {
1864 const size_t ndata = in->nbytes / in->data_size;
1865 const matvar_t *const *indata = (const matvar_t *const *)in->data;
1866 const matvar_t **outdata = (const matvar_t **)out->data;
1867 for ( i = 0; i < ndata; i++ ) {
1868 outdata[i] = Mat_VarDuplicate(indata[i], opt);
1869 }
1870 }
1871 } else if ( in->data != NULL && in->class_type == MAT_C_SPARSE ) {
1872 out->data = malloc(sizeof(mat_sparse_t));
1873 if ( out->data != NULL ) {
1874 mat_sparse_t *out_sparse = (mat_sparse_t *)out->data;
1875 const mat_sparse_t *in_sparse = (mat_sparse_t *)in->data;
1876 out_sparse->nzmax = in_sparse->nzmax;
1877 out_sparse->nir = in_sparse->nir;
1878 out_sparse->ir = (mat_uint32_t *)malloc(in_sparse->nir * sizeof(*out_sparse->ir));
1879 if ( out_sparse->ir != NULL )
1880 memcpy(out_sparse->ir, in_sparse->ir, in_sparse->nir * sizeof(*out_sparse->ir));
1881 out_sparse->njc = in_sparse->njc;
1882 out_sparse->jc = (mat_uint32_t *)malloc(in_sparse->njc * sizeof(*out_sparse->jc));
1883 if ( out_sparse->jc != NULL )
1884 memcpy(out_sparse->jc, in_sparse->jc, in_sparse->njc * sizeof(*out_sparse->jc));
1885 out_sparse->ndata = in_sparse->ndata;
1886 if ( out->isComplex && NULL != in_sparse->data ) {
1887 out_sparse->data = malloc(sizeof(mat_complex_split_t));
1888 if ( out_sparse->data != NULL ) {
1889 mat_complex_split_t *out_data = (mat_complex_split_t *)out_sparse->data;
1890 const mat_complex_split_t *in_data =
1891 (const mat_complex_split_t *)in_sparse->data;
1892 out_data->Re = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1893 if ( NULL != out_data->Re )
1894 memcpy(out_data->Re, in_data->Re,
1895 in_sparse->ndata * Mat_SizeOf(in->data_type));
1896 out_data->Im = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1897 if ( NULL != out_data->Im )
1898 memcpy(out_data->Im, in_data->Im,
1899 in_sparse->ndata * Mat_SizeOf(in->data_type));
1900 }
1901 } else if ( in_sparse->data != NULL ) {
1902 out_sparse->data = malloc(in_sparse->ndata * Mat_SizeOf(in->data_type));
1903 if ( NULL != out_sparse->data )
1904 memcpy(out_sparse->data, in_sparse->data,
1905 in_sparse->ndata * Mat_SizeOf(in->data_type));
1906 } else {
1907 out_sparse->data = NULL;
1908 }
1909 }
1910 } else if ( in->data != NULL && in->nbytes != 0 ) {
1911 if ( out->isComplex ) {
1912 out->data = malloc(sizeof(mat_complex_split_t));
1913 if ( out->data != NULL ) {
1914 mat_complex_split_t *out_data = (mat_complex_split_t *)out->data;
1915 const mat_complex_split_t *in_data = (const mat_complex_split_t *)in->data;
1916 out_data->Re = malloc(out->nbytes);
1917 if ( NULL != out_data->Re )
1918 memcpy(out_data->Re, in_data->Re, out->nbytes);
1919 out_data->Im = malloc(out->nbytes);
1920 if ( NULL != out_data->Im )
1921 memcpy(out_data->Im, in_data->Im, out->nbytes);
1922 }
1923 } else {
1924 out->data = malloc(in->nbytes);
1925 if ( out->data != NULL )
1926 memcpy(out->data, in->data, in->nbytes);
1927 }
1928 }
1929
1930 return out;
1931 }
1932
1933 /** @brief Frees all the allocated memory associated with the structure
1934 *
1935 * Frees memory used by a MAT variable. Frees the data associated with a
1936 * MAT variable if it's non-NULL and MAT_F_DONT_COPY_DATA was not used.
1937 * @ingroup MAT
1938 * @param matvar Pointer to the matvar_t structure
1939 */
1940 void
1941 Mat_VarFree(matvar_t *matvar)
1942 {
1943 size_t nelems = 0;
1944 int err;
1945
1946 if ( NULL == matvar )
1947 return;
1948 if ( NULL != matvar->dims ) {
1949 nelems = 1;
1950 err = Mat_MulDims(matvar, &nelems);
1951 free(matvar->dims);
1952 } else {
1953 err = MATIO_E_BAD_ARGUMENT;
1954 }
1955 if ( NULL != matvar->data ) {
1956 switch ( matvar->class_type ) {
1957 case MAT_C_STRUCT:
1958 if ( !matvar->mem_conserve ) {
1959 if ( MATIO_E_NO_ERROR == err ) {
1960 matvar_t **fields = (matvar_t **)matvar->data;
1961 size_t nelems_x_nfields;
1962 err = Mul(&nelems_x_nfields, nelems, matvar->internal->num_fields);
1963 if ( MATIO_E_NO_ERROR == err && nelems_x_nfields > 0 ) {
1964 size_t i;
1965 for ( i = 0; i < nelems_x_nfields; i++ )
1966 Mat_VarFree(fields[i]);
1967 }
1968 }
1969 free(matvar->data);
1970 }
1971 break;
1972 case MAT_C_CELL:
1973 if ( !matvar->mem_conserve ) {
1974 if ( MATIO_E_NO_ERROR == err ) {
1975 matvar_t **cells = (matvar_t **)matvar->data;
1976 size_t i;
1977 for ( i = 0; i < nelems; i++ )
1978 Mat_VarFree(cells[i]);
1979 }
1980 free(matvar->data);
1981 }
1982 break;
1983 case MAT_C_SPARSE:
1984 if ( !matvar->mem_conserve ) {
1985 mat_sparse_t *sparse;
1986 sparse = (mat_sparse_t *)matvar->data;
1987 if ( sparse->ir != NULL )
1988 free(sparse->ir);
1989 if ( sparse->jc != NULL )
1990 free(sparse->jc);
1991 if ( matvar->isComplex && NULL != sparse->data ) {
1992 ComplexFree((mat_complex_split_t *)sparse->data);
1993 } else if ( sparse->data != NULL ) {
1994 free(sparse->data);
1995 }
1996 free(sparse);
1997 }
1998 break;
1999 case MAT_C_DOUBLE:
2000 case MAT_C_SINGLE:
2001 case MAT_C_INT64:
2002 case MAT_C_UINT64:
2003 case MAT_C_INT32:
2004 case MAT_C_UINT32:
2005 case MAT_C_INT16:
2006 case MAT_C_UINT16:
2007 case MAT_C_INT8:
2008 case MAT_C_UINT8:
2009 case MAT_C_CHAR:
2010 if ( !matvar->mem_conserve ) {
2011 if ( matvar->isComplex ) {
2012 ComplexFree((mat_complex_split_t *)matvar->data);
2013 } else {
2014 free(matvar->data);
2015 }
2016 }
2017 break;
2018 case MAT_C_FUNCTION:
2019 if ( !matvar->mem_conserve ) {
2020 size_t i;
2021 matvar_t **functions = (matvar_t **)matvar->data;
2022 for ( i = 0; i < nelems; i++ ) {
2023 Mat_VarFree(functions[i]);
2024 }
2025 free(matvar->data);
2026 }
2027 break;
2028 case MAT_C_EMPTY:
2029 case MAT_C_OBJECT:
2030 case MAT_C_OPAQUE:
2031 break;
2032 }
2033 }
2034
2035 if ( NULL != matvar->internal ) {
2036 #if HAVE_ZLIB
2037 if ( matvar->compression == MAT_COMPRESSION_ZLIB ) {
2038 inflateEnd(matvar->internal->z);
2039 free(matvar->internal->z);
2040 if ( matvar->class_type == MAT_C_SPARSE && NULL != matvar->internal->data ) {
2041 mat_sparse_t *sparse;
2042 sparse = (mat_sparse_t *)matvar->internal->data;
2043 if ( sparse->ir != NULL )
2044 free(sparse->ir);
2045 if ( sparse->jc != NULL )
2046 free(sparse->jc);
2047 if ( matvar->isComplex && NULL != sparse->data ) {
2048 ComplexFree((mat_complex_split_t *)sparse->data);
2049 } else if ( sparse->data != NULL ) {
2050 free(sparse->data);
2051 }
2052 free(sparse);
2053 } else if ( matvar->isComplex && NULL != matvar->internal->data ) {
2054 ComplexFree((mat_complex_split_t *)matvar->internal->data);
2055 } else if ( NULL != matvar->internal->data ) {
2056 free(matvar->internal->data);
2057 }
2058 }
2059 #endif
2060 #if defined(MAT73) && MAT73
2061 if ( H5I_INVALID_HID != matvar->internal->id ) {
2062 switch ( H5Iget_type(matvar->internal->id) ) {
2063 case H5I_GROUP:
2064 H5Gclose(matvar->internal->id);
2065 matvar->internal->id = H5I_INVALID_HID;
2066 break;
2067 case H5I_DATASET:
2068 H5Dclose(matvar->internal->id);
2069 matvar->internal->id = H5I_INVALID_HID;
2070 break;
2071 default:
2072 break;
2073 }
2074 }
2075 #endif
2076 if ( NULL != matvar->internal->fieldnames && matvar->internal->num_fields > 0 ) {
2077 size_t i;
2078 for ( i = 0; i < matvar->internal->num_fields; i++ ) {
2079 if ( NULL != matvar->internal->fieldnames[i] )
2080 free(matvar->internal->fieldnames[i]);
2081 }
2082 free(matvar->internal->fieldnames);
2083 }
2084 free(matvar->internal);
2085 matvar->internal = NULL;
2086 }
2087 if ( NULL != matvar->name )
2088 free(matvar->name);
2089 free(matvar);
2090 }
2091
2092 /** @brief Calculate a single subscript from a set of subscript values
2093 *
2094 * Calculates a single linear subscript (0-relative) given a 1-relative
2095 * subscript for each dimension. The calculation uses the formula below where
2096 * index is the linear index, s is an array of length RANK where each element
2097 * is the subscript for the corresponding dimension, D is an array whose
2098 * elements are the dimensions of the variable.
2099 * \f[
2100 * index = \sum\limits_{k=0}^{RANK-1} [(s_k - 1) \prod\limits_{l=0}^{k} D_l ]
2101 * \f]
2102 * @ingroup MAT
2103 * @param rank Rank of the variable
2104 * @param dims Dimensions of the variable
2105 * @param subs Array of dimension subscripts
2106 * @return Single (linear) subscript
2107 */
2108 int
2109 Mat_CalcSingleSubscript(int rank, const int *dims, const int *subs)
2110 {
2111 int index = 0, i, j, err = MATIO_E_NO_ERROR;
2112
2113 for ( i = 0; i < rank; i++ ) {
2114 int k = subs[i];
2115 if ( k > dims[i] ) {
2116 err = MATIO_E_BAD_ARGUMENT;
2117 Mat_Critical("Mat_CalcSingleSubscript: index out of bounds");
2118 break;
2119 } else if ( k < 1 ) {
2120 err = MATIO_E_BAD_ARGUMENT;
2121 break;
2122 }
2123 k--;
2124 for ( j = i; j--; )
2125 k *= dims[j];
2126 index += k;
2127 }
2128 if ( err )
2129 index = -1;
2130
2131 return index;
2132 }
2133
2134 /** @brief Calculate a single subscript from a set of subscript values
2135 *
2136 * Calculates a single linear subscript (0-relative) given a 1-relative
2137 * subscript for each dimension. The calculation uses the formula below where
2138 * index is the linear index, s is an array of length RANK where each element
2139 * is the subscript for the corresponding dimension, D is an array whose
2140 * elements are the dimensions of the variable.
2141 * \f[
2142 * index = \sum\limits_{k=0}^{RANK-1} [(s_k - 1) \prod\limits_{l=0}^{k} D_l ]
2143 * \f]
2144 * @ingroup MAT
2145 * @param rank Rank of the variable
2146 * @param dims Dimensions of the variable
2147 * @param subs Array of dimension subscripts
2148 * @param[out] index Single (linear) subscript
2149 * @retval 0 on success
2150 */
2151 int
2152 Mat_CalcSingleSubscript2(int rank, const size_t *dims, const size_t *subs, size_t *index)
2153 {
2154 int i, err = MATIO_E_NO_ERROR;
2155
2156 for ( i = 0; i < rank; i++ ) {
2157 int j;
2158 size_t k = subs[i];
2159 if ( k > dims[i] ) {
2160 err = MATIO_E_BAD_ARGUMENT;
2161 Mat_Critical("Mat_CalcSingleSubscript2: index out of bounds");
2162 break;
2163 } else if ( k < 1 ) {
2164 err = MATIO_E_BAD_ARGUMENT;
2165 break;
2166 }
2167 k--;
2168 for ( j = i; j--; )
2169 k *= dims[j];
2170 *index += k;
2171 }
2172
2173 return err;
2174 }
2175
2176 /** @brief Calculate a set of subscript values from a single(linear) subscript
2177 *
2178 * Calculates 1-relative subscripts for each dimension given a 0-relative
2179 * linear index. Subscripts are calculated as follows where s is the array
2180 * of dimension subscripts, D is the array of dimensions, and index is the
2181 * linear index.
2182 * \f[
2183 * s_k = \lfloor\frac{1}{L} \prod\limits_{l = 0}^{k} D_l\rfloor + 1
2184 * \f]
2185 * \f[
2186 * L = index - \sum\limits_{l = k}^{RANK - 1} s_k \prod\limits_{m = 0}^{k} D_m
2187 * \f]
2188 * @ingroup MAT
2189 * @param rank Rank of the variable
2190 * @param dims Dimensions of the variable
2191 * @param index Linear index
2192 * @return Array of dimension subscripts
2193 */
2194 int *
2195 Mat_CalcSubscripts(int rank, const int *dims, int index)
2196 {
2197 int i, j, *subs;
2198 double l;
2199
2200 subs = (int *)malloc(rank * sizeof(int));
2201 if ( NULL == subs ) {
2202 return subs;
2203 }
2204
2205 l = index;
2206 for ( i = rank; i--; ) {
2207 int k = 1;
2208 for ( j = i; j--; )
2209 k *= dims[j];
2210 subs[i] = (int)floor(l / (double)k);
2211 l -= subs[i] * k;
2212 subs[i]++;
2213 }
2214
2215 return subs;
2216 }
2217
2218 /** @brief Calculate a set of subscript values from a single(linear) subscript
2219 *
2220 * Calculates 1-relative subscripts for each dimension given a 0-relative
2221 * linear index. Subscripts are calculated as follows where s is the array
2222 * of dimension subscripts, D is the array of dimensions, and index is the
2223 * linear index.
2224 * \f[
2225 * s_k = \lfloor\frac{1}{L} \prod\limits_{l = 0}^{k} D_l\rfloor + 1
2226 * \f]
2227 * \f[
2228 * L = index - \sum\limits_{l = k}^{RANK - 1} s_k \prod\limits_{m = 0}^{k} D_m
2229 * \f]
2230 * @ingroup MAT
2231 * @param rank Rank of the variable
2232 * @param dims Dimensions of the variable
2233 * @param index Linear index
2234 * @return Array of dimension subscripts
2235 */
2236 size_t *
2237 Mat_CalcSubscripts2(int rank, const size_t *dims, size_t index)
2238 {
2239 int i;
2240 size_t *subs;
2241 double l;
2242
2243 subs = (size_t *)malloc(rank * sizeof(size_t));
2244 if ( NULL == subs ) {
2245 return subs;
2246 }
2247
2248 l = (double)index;
2249 for ( i = rank; i--; ) {
2250 int j;
2251 size_t k = 1;
2252 for ( j = i; j--; )
2253 k *= dims[j];
2254 subs[i] = (size_t)floor(l / (double)k);
2255 l -= (double)(subs[i] * k);
2256 subs[i]++;
2257 }
2258
2259 return subs;
2260 }
2261
2262 /** @brief Calculates the size of a matlab variable in bytes
2263 *
2264 * @ingroup MAT
2265 * @param matvar matlab variable
2266 * @returns size of the variable in bytes, or 0 on error
2267 */
2268 size_t
2269 Mat_VarGetSize(const matvar_t *matvar)
2270 {
2271 int err;
2272 size_t i;
2273 size_t bytes = 0, overhead = 0, ptr = 0;
2274
2275 #if defined(_WIN64) || (defined(__SIZEOF_POINTER__) && (__SIZEOF_POINTER__ == 8)) || \
2276 (defined(SIZEOF_VOID_P) && (SIZEOF_VOID_P == 8))
2277 /* 112 bytes cell/struct overhead for 64-bit system */
2278 overhead = 112;
2279 ptr = 8;
2280 #elif defined(_WIN32) || (defined(__SIZEOF_POINTER__) && (__SIZEOF_POINTER__ == 4)) || \
2281 (defined(SIZEOF_VOID_P) && (SIZEOF_VOID_P == 4))
2282 /* 60 bytes cell/struct overhead for 32-bit system */
2283 overhead = 60;
2284 ptr = 4;
2285 #endif
2286
2287 if ( matvar->class_type == MAT_C_STRUCT ) {
2288 matvar_t **fields = (matvar_t **)matvar->data;
2289 size_t field_name_length;
2290 if ( NULL != fields ) {
2291 size_t nelems_x_nfields = matvar->internal->num_fields;
2292 err = Mat_MulDims(matvar, &nelems_x_nfields);
2293 err |= Mul(&bytes, nelems_x_nfields, overhead);
2294 if ( err )
2295 return 0;
2296
2297 for ( i = 0; i < nelems_x_nfields; i++ ) {
2298 if ( NULL != fields[i] ) {
2299 if ( MAT_C_EMPTY != fields[i]->class_type ) {
2300 err = Add(&bytes, bytes, Mat_VarGetSize(fields[i]));
2301 if ( err )
2302 return 0;
2303 } else {
2304 bytes -= overhead;
2305 bytes += ptr;
2306 }
2307 }
2308 }
2309 }
2310 err = Mul(&field_name_length, 64 /* max field name length */, matvar->internal->num_fields);
2311 err |= Add(&bytes, bytes, field_name_length);
2312 if ( err )
2313 return 0;
2314 } else if ( matvar->class_type == MAT_C_CELL ) {
2315 matvar_t **cells = (matvar_t **)matvar->data;
2316 if ( NULL != cells ) {
2317 size_t nelems = matvar->nbytes / matvar->data_size;
2318 err = Mul(&bytes, nelems, overhead);
2319 if ( err )
2320 return 0;
2321
2322 for ( i = 0; i < nelems; i++ ) {
2323 if ( NULL != cells[i] ) {
2324 if ( MAT_C_EMPTY != cells[i]->class_type ) {
2325 err = Add(&bytes, bytes, Mat_VarGetSize(cells[i]));
2326 if ( err )
2327 return 0;
2328 } else {
2329 bytes -= overhead;
2330 bytes += ptr;
2331 }
2332 }
2333 }
2334 }
2335 } else if ( matvar->class_type == MAT_C_SPARSE ) {
2336 const mat_sparse_t *sparse = (const mat_sparse_t *)matvar->data;
2337 if ( NULL != sparse ) {
2338 size_t sparse_size = 0;
2339 err = Mul(&bytes, sparse->ndata, Mat_SizeOf(matvar->data_type));
2340 if ( err )
2341 return 0;
2342
2343 if ( matvar->isComplex ) {
2344 err = Mul(&bytes, bytes, 2);
2345 if ( err )
2346 return 0;
2347 }
2348
2349 #if defined(_WIN64) || (defined(__SIZEOF_POINTER__) && (__SIZEOF_POINTER__ == 8)) || \
2350 (defined(SIZEOF_VOID_P) && (SIZEOF_VOID_P == 8))
2351 /* 8 byte integers for 64-bit system (as displayed in MATLAB (x64) whos) */
2352 err = Mul(&sparse_size, sparse->nir + sparse->njc, 8);
2353 #elif defined(_WIN32) || (defined(__SIZEOF_POINTER__) && (__SIZEOF_POINTER__ == 4)) || \
2354 (defined(SIZEOF_VOID_P) && (SIZEOF_VOID_P == 4))
2355 /* 4 byte integers for 32-bit system (as defined by mat_sparse_t) */
2356 err = Mul(&sparse_size, sparse->nir + sparse->njc, 4);
2357 #endif
2358 err |= Add(&bytes, bytes, sparse_size);
2359 if ( err )
2360 return 0;
2361
2362 if ( sparse->ndata == 0 || sparse->nir == 0 || sparse->njc == 0 ) {
2363 err = Add(&bytes, bytes, matvar->isLogical ? 1 : 8);
2364 if ( err )
2365 return 0;
2366 }
2367 }
2368 } else {
2369 if ( matvar->rank > 0 ) {
2370 bytes = Mat_SizeOfClass(matvar->class_type);
2371 err = Mat_MulDims(matvar, &bytes);
2372 if ( err )
2373 return 0;
2374
2375 if ( matvar->isComplex ) {
2376 err = Mul(&bytes, bytes, 2);
2377 if ( err )
2378 return 0;
2379 }
2380 }
2381 }
2382
2383 return bytes;
2384 }
2385
2386 /** @brief Prints the variable information
2387 *
2388 * Prints to stdout the values of the @ref matvar_t structure
2389 * @ingroup MAT
2390 * @param matvar Pointer to the matvar_t structure
2391 * @param printdata set to 1 if the Variables data should be printed, else 0
2392 */
2393 void
2394 Mat_VarPrint(const matvar_t *matvar, int printdata)
2395 {
2396 size_t nelems = 0, i;
2397 const char *class_type_desc[18] = {"Undefined",
2398 "Cell Array",
2399 "Structure",
2400 "Object",
2401 "Character Array",
2402 "Sparse Array",
2403 "Double Precision Array",
2404 "Single Precision Array",
2405 "8-bit, signed integer array",
2406 "8-bit, unsigned integer array",
2407 "16-bit, signed integer array",
2408 "16-bit, unsigned integer array",
2409 "32-bit, signed integer array",
2410 "32-bit, unsigned integer array",
2411 "64-bit, signed integer array",
2412 "64-bit, unsigned integer array",
2413 "Function",
2414 "Opaque"};
2415
2416 if ( matvar == NULL )
2417 return;
2418 if ( NULL != matvar->name )
2419 printf(" Name: %s\n", matvar->name);
2420 printf(" Rank: %d\n", matvar->rank);
2421 if ( matvar->rank <= 0 )
2422 return;
2423 if ( NULL != matvar->dims ) {
2424 int err;
2425 nelems = 1;
2426 err = Mat_MulDims(matvar, &nelems);
2427 printf("Dimensions: %" SIZE_T_FMTSTR, matvar->dims[0]);
2428 if ( MATIO_E_NO_ERROR == err ) {
2429 int k;
2430 for ( k = 1; k < matvar->rank; k++ ) {
2431 printf(" x %" SIZE_T_FMTSTR, matvar->dims[k]);
2432 }
2433 }
2434 printf("\n");
2435 }
2436 printf("Class Type: %s", class_type_desc[matvar->class_type]);
2437 if ( matvar->isComplex )
2438 printf(" (complex)");
2439 else if ( matvar->isLogical )
2440 printf(" (logical)");
2441 printf("\n");
2442 if ( matvar->data_type ) {
2443 const char *data_type_desc[25] = {"Unknown",
2444 "8-bit, signed integer",
2445 "8-bit, unsigned integer",
2446 "16-bit, signed integer",
2447 "16-bit, unsigned integer",
2448 "32-bit, signed integer",
2449 "32-bit, unsigned integer",
2450 "IEEE 754 single-precision",
2451 "RESERVED",
2452 "IEEE 754 double-precision",
2453 "RESERVED",
2454 "RESERVED",
2455 "64-bit, signed integer",
2456 "64-bit, unsigned integer",
2457 "Matlab Array",
2458 "Compressed Data",
2459 "Unicode UTF-8 Encoded Character Data",
2460 "Unicode UTF-16 Encoded Character Data",
2461 "Unicode UTF-32 Encoded Character Data",
2462 "RESERVED",
2463 "String",
2464 "Cell Array",
2465 "Structure",
2466 "Array",
2467 "Function"};
2468 printf(" Data Type: %s\n", data_type_desc[matvar->data_type]);
2469 }
2470
2471 if ( MAT_C_STRUCT == matvar->class_type ) {
2472 matvar_t **fields = (matvar_t **)matvar->data;
2473 size_t nfields = matvar->internal->num_fields;
2474 size_t nelems_x_nfields = 1;
2475 int err = Mul(&nelems_x_nfields, nelems, nfields);
2476 if ( MATIO_E_NO_ERROR == err && nelems_x_nfields > 0 ) {
2477 printf("Fields[%" SIZE_T_FMTSTR "] {\n", nelems_x_nfields);
2478 if ( NULL != matvar->internal->fieldnames && NULL != fields ) {
2479 for ( i = 0; i < nelems_x_nfields; i++ ) {
2480 if ( NULL == fields[i] ) {
2481 printf(" Name: %s\n Rank: %d\n",
2482 matvar->internal->fieldnames[i % nfields], 0);
2483 } else {
2484 Mat_VarPrint(fields[i], printdata);
2485 }
2486 }
2487 }
2488 printf("}\n");
2489 } else {
2490 printf("Fields[%" SIZE_T_FMTSTR "] {\n", nfields);
2491 for ( i = 0; i < nfields; i++ )
2492 printf(" Name: %s\n Rank: %d\n", matvar->internal->fieldnames[i], 0);
2493 printf("}\n");
2494 }
2495 return;
2496 }
2497 if ( matvar->data == NULL || matvar->data_size < 1 ) {
2498 if ( printdata )
2499 printf("{\n}\n");
2500 return;
2501 }
2502 if ( MAT_C_CELL == matvar->class_type ) {
2503 matvar_t **cells = (matvar_t **)matvar->data;
2504 nelems = matvar->nbytes / matvar->data_size;
2505 printf("{\n");
2506 for ( i = 0; i < nelems; i++ )
2507 Mat_VarPrint(cells[i], printdata);
2508 printf("}\n");
2509 return;
2510 }
2511 if ( !printdata )
2512 return;
2513
2514 printf("{\n");
2515 Mat_PrintData(matvar->rank, matvar->dims, matvar->data, matvar->class_type, matvar->isComplex,
2516 matvar->data_type, matvar->nbytes, nelems);
2517 printf("}\n");
2518 }
2519
2520 /** @brief Reads MAT variable data from a file
2521 *
2522 * Reads data from a MAT variable. The variable must have been read by
2523 * Mat_VarReadInfo.
2524 * @ingroup MAT
2525 * @param mat MAT file to read data from
2526 * @param matvar MAT variable information
2527 * @param data pointer to store data in (must be pre-allocated)
2528 * @param start array of starting indices
2529 * @param stride stride of data
2530 * @param edge array specifying the number to read in each direction
2531 * @retval 0 on success
2532 */
2533 int
2534 Mat_VarReadData(mat_t *mat, matvar_t *matvar, void *data, const int *start, const int *stride,
2535 const int *edge)
2536 {
2537 int err = MATIO_E_NO_ERROR;
2538
2539 switch ( matvar->class_type ) {
2540 case MAT_C_DOUBLE:
2541 case MAT_C_SINGLE:
2542 case MAT_C_INT64:
2543 case MAT_C_UINT64:
2544 case MAT_C_INT32:
2545 case MAT_C_UINT32:
2546 case MAT_C_INT16:
2547 case MAT_C_UINT16:
2548 case MAT_C_INT8:
2549 case MAT_C_UINT8:
2550 break;
2551 default:
2552 return MATIO_E_OPERATION_NOT_SUPPORTED;
2553 }
2554
2555 switch ( mat->version ) {
2556 case MAT_FT_MAT5:
2557 err = Mat_VarReadData5(mat, matvar, data, start, stride, edge);
2558 break;
2559 case MAT_FT_MAT73:
2560 #if defined(MAT73) && MAT73
2561 err = Mat_VarReadData73(mat, matvar, data, start, stride, edge);
2562 #else
2563 err = MATIO_E_OPERATION_NOT_SUPPORTED;
2564 #endif
2565 break;
2566 case MAT_FT_MAT4:
2567 err = Mat_VarReadData4(mat, matvar, data, start, stride, edge);
2568 break;
2569 default:
2570 err = MATIO_E_FAIL_TO_IDENTIFY;
2571 break;
2572 }
2573
2574 return err;
2575 }
2576
2577 /** @brief Reads all the data for a matlab variable
2578 *
2579 * Allocates memory and reads the data for a given matlab variable.
2580 * @ingroup MAT
2581 * @param mat Matlab MAT file structure pointer
2582 * @param matvar Variable whose data is to be read
2583 * @returns non-zero on error
2584 */
2585 int
2586 Mat_VarReadDataAll(mat_t *mat, matvar_t *matvar)
2587 {
2588 int err = MATIO_E_NO_ERROR;
2589
2590 if ( mat == NULL || matvar == NULL )
2591 err = MATIO_E_BAD_ARGUMENT;
2592 else
2593 err = ReadData(mat, matvar);
2594
2595 return err;
2596 }
2597
2598 /** @brief Reads a subset of a MAT variable using a 1-D indexing
2599 *
2600 * Reads data from a MAT variable using a linear (1-D) indexing mode. The
2601 * variable must have been read by Mat_VarReadInfo.
2602 * @ingroup MAT
2603 * @param mat MAT file to read data from
2604 * @param matvar MAT variable information
2605 * @param data pointer to store data in (must be pre-allocated)
2606 * @param start starting index
2607 * @param stride stride of data
2608 * @param edge number of elements to read
2609 * @retval 0 on success
2610 */
2611 int
2612 Mat_VarReadDataLinear(mat_t *mat, matvar_t *matvar, void *data, int start, int stride, int edge)
2613 {
2614 int err = MATIO_E_NO_ERROR;
2615
2616 switch ( matvar->class_type ) {
2617 case MAT_C_DOUBLE:
2618 case MAT_C_SINGLE:
2619 case MAT_C_INT64:
2620 case MAT_C_UINT64:
2621 case MAT_C_INT32:
2622 case MAT_C_UINT32:
2623 case MAT_C_INT16:
2624 case MAT_C_UINT16:
2625 case MAT_C_INT8:
2626 case MAT_C_UINT8:
2627 break;
2628 default:
2629 return MATIO_E_OPERATION_NOT_SUPPORTED;
2630 }
2631
2632 switch ( mat->version ) {
2633 case MAT_FT_MAT5:
2634 err = Mat_VarReadDataLinear5(mat, matvar, data, start, stride, edge);
2635 break;
2636 case MAT_FT_MAT73:
2637 #if defined(MAT73) && MAT73
2638 err = Mat_VarReadDataLinear73(mat, matvar, data, start, stride, edge);
2639 #else
2640 err = MATIO_E_OPERATION_NOT_SUPPORTED;
2641 #endif
2642 break;
2643 case MAT_FT_MAT4:
2644 err = Mat_VarReadDataLinear4(mat, matvar, data, start, stride, edge);
2645 break;
2646 default:
2647 err = MATIO_E_FAIL_TO_IDENTIFY;
2648 break;
2649 }
2650
2651 return err;
2652 }
2653
2654 /** @brief Reads the information of the next variable in a MAT file
2655 *
2656 * Reads the next variable's information (class,flags-complex/global/logical,
2657 * rank,dimensions, name, etc) from the Matlab MAT file. After reading, the MAT
2658 * file is positioned past the current variable.
2659 * @ingroup MAT
2660 * @param mat Pointer to the MAT file
2661 * @return Pointer to the @ref matvar_t structure containing the MAT
2662 * variable information
2663 */
2664 matvar_t *
2665 Mat_VarReadNextInfo(mat_t *mat)
2666 {
2667 return Mat_VarReadNextInfoPredicate(mat, NULL, NULL);
2668 }
2669
2670 /** @brief Reads the information of the next variable in a filtered MAT file
2671 *
2672 * Reads the next variable's information (class,flags-complex/global/logical,
2673 * rank,dimensions, name, etc) from the Matlab MAT file. Calls a user callback
2674 * to check where the variable has to be fully read or skipped.
2675 * If skipped tries to read next till accepted or EOF.
2676 * After reading, the MAT file is positioned past the current variable.
2677 * @ingroup MAT
2678 * @param mat Pointer to the MAT file
2679 * @param pred User callback function
2680 * @param user_data User data to be passed to the callback function
2681 * @return Pointer to the @ref matvar_t structure containing the MAT
2682 * variable information
2683 */
2684 matvar_t *
2685 Mat_VarReadNextInfoPredicate(mat_t *mat, mat_iter_pred_t pred, const void *user_data)
2686 {
2687 matvar_t *matvar;
2688 if ( mat == NULL )
2689 return NULL;
2690
2691 switch ( mat->version ) {
2692 case MAT_FT_MAT5:
2693 matvar = Mat_VarReadNextInfo5(mat);
2694 break;
2695 case MAT_FT_MAT73:
2696 #if defined(MAT73) && MAT73
2697 matvar = Mat_VarReadNextInfo73(mat, pred, user_data);
2698 #else
2699 matvar = NULL;
2700 #endif
2701 break;
2702 case MAT_FT_MAT4:
2703 matvar = Mat_VarReadNextInfo4(mat);
2704 break;
2705 default:
2706 matvar = NULL;
2707 break;
2708 }
2709
2710 return matvar;
2711 }
2712
2713 #if defined(MAT73) && MAT73
2714 static int
2715 Mat_IteratorNameAcceptor(const char *name, const void *user_data)
2716 {
2717 const char *required_name = (const char *)user_data;
2718 return (NULL != name) && (NULL != required_name) && 0 == strcmp(name, required_name);
2719 }
2720 #endif
2721
2722 /** @brief Reads the information of a variable with the given name from a MAT file
2723 *
2724 * Reads the named variable (or the next variable if name is NULL) information
2725 * (class,flags-complex/global/logical,rank,dimensions,and name) from the
2726 * Matlab MAT file
2727 * @ingroup MAT
2728 * @param mat Pointer to the MAT file
2729 * @param name Name of the variable to read
2730 * @return Pointer to the @ref matvar_t structure containing the MAT
2731 * variable information
2732 */
2733 matvar_t *
2734 Mat_VarReadInfo(mat_t *mat, const char *name)
2735 {
2736 matvar_t *matvar = NULL;
2737
2738 if ( mat == NULL || name == NULL )
2739 return NULL;
2740
2741 if ( mat->version == MAT_FT_MAT73 ) {
2742 size_t fpos = mat->next_index;
2743 mat->next_index = 0;
2744 while ( NULL == matvar && mat->next_index < mat->num_datasets ) {
2745 #if defined(MAT73) && MAT73
2746 matvar = Mat_VarReadNextInfoPredicate(mat, Mat_IteratorNameAcceptor, name);
2747 if ( NULL == matvar ) {
2748 Mat_Critical("An error occurred in reading the MAT file");
2749 break;
2750 }
2751 #else
2752 matvar = Mat_VarReadNextInfo(mat);
2753 if ( matvar != NULL ) {
2754 if ( matvar->name == NULL || 0 != strcmp(matvar->name, name) ) {
2755 Mat_VarFree(matvar);
2756 matvar = NULL;
2757 }
2758 } else {
2759 Mat_Critical("An error occurred in reading the MAT file");
2760 break;
2761 }
2762 #endif
2763 }
2764 mat->next_index = fpos;
2765 } else {
2766 mat_off_t fpos = ftello((FILE *)mat->fp);
2767 if ( fpos != -1L ) {
2768 (void)fseeko((FILE *)mat->fp, mat->bof, SEEK_SET);
2769 do {
2770 matvar = Mat_VarReadNextInfo(mat);
2771 if ( matvar != NULL ) {
2772 if ( matvar->name == NULL || 0 != strcmp(matvar->name, name) ) {
2773 Mat_VarFree(matvar);
2774 matvar = NULL;
2775 }
2776 } else if ( !IsEndOfFile((FILE *)mat->fp, NULL) ) {
2777 Mat_Critical("An error occurred in reading the MAT file");
2778 break;
2779 }
2780 } while ( NULL == matvar && !IsEndOfFile((FILE *)mat->fp, NULL) );
2781 (void)fseeko((FILE *)mat->fp, fpos, SEEK_SET);
2782 } else {
2783 Mat_Critical("Couldn't determine file position");
2784 }
2785 }
2786
2787 return matvar;
2788 }
2789
2790 /** @brief Reads the variable with the given name from a MAT file
2791 *
2792 * Reads the next variable in the Matlab MAT file
2793 * @ingroup MAT
2794 * @param mat Pointer to the MAT file
2795 * @param name Name of the variable to read
2796 * @return Pointer to the @ref matvar_t structure containing the MAT
2797 * variable information
2798 */
2799 matvar_t *
2800 Mat_VarRead(mat_t *mat, const char *name)
2801 {
2802 matvar_t *matvar = NULL;
2803
2804 if ( mat == NULL || name == NULL )
2805 return NULL;
2806
2807 if ( MAT_FT_MAT73 != mat->version ) {
2808 mat_off_t fpos = ftello((FILE *)mat->fp);
2809 if ( fpos == -1L ) {
2810 Mat_Critical("Couldn't determine file position");
2811 return NULL;
2812 }
2813 matvar = Mat_VarReadInfo(mat, name);
2814 if ( matvar != NULL ) {
2815 const int err = ReadData(mat, matvar);
2816 if ( err ) {
2817 Mat_VarFree(matvar);
2818 matvar = NULL;
2819 }
2820 }
2821 (void)fseeko((FILE *)mat->fp, fpos, SEEK_SET);
2822 } else {
2823 size_t fpos = mat->next_index;
2824 mat->next_index = 0;
2825 matvar = Mat_VarReadInfo(mat, name);
2826 if ( matvar != NULL ) {
2827 const int err = ReadData(mat, matvar);
2828 if ( err ) {
2829 Mat_VarFree(matvar);
2830 matvar = NULL;
2831 }
2832 }
2833 mat->next_index = fpos;
2834 }
2835
2836 return matvar;
2837 }
2838
2839 /** @brief Reads the next variable in a MAT file
2840 *
2841 * Reads the next variable in the Matlab MAT file
2842 * @ingroup MAT
2843 * @param mat Pointer to the MAT file
2844 * @return Pointer to the @ref matvar_t structure containing the MAT
2845 * variable information
2846 */
2847 matvar_t *
2848 Mat_VarReadNext(mat_t *mat)
2849 {
2850 return Mat_VarReadNextPredicate(mat, NULL, NULL);
2851 }
2852
2853 /** @brief Reads the next variable in a filtered MAT file
2854 *
2855 * Reads the next variable in the Matlab MAT file. Calls a user callback
2856 * to check where the variable has to be fully read of skipped.
2857 * If skipped tries to read next till accepted or EOF.
2858 *
2859 * @ingroup MAT
2860 * @param mat Pointer to the MAT file
2861 * @return Pointer to the @ref matvar_t structure containing the MAT
2862 * variable information
2863 */
2864 matvar_t *
2865 Mat_VarReadNextPredicate(mat_t *mat, mat_iter_pred_t pred, const void *user_data)
2866 {
2867 mat_off_t fpos = 0;
2868 matvar_t *matvar = NULL;
2869
2870 do {
2871 Mat_VarFree(matvar);
2872 if ( mat->version != MAT_FT_MAT73 ) {
2873 if ( IsEndOfFile((FILE *)mat->fp, &fpos) )
2874 return NULL;
2875 if ( fpos == -1L ) {
2876 return NULL;
2877 }
2878 }
2879 matvar = Mat_VarReadNextInfoPredicate(mat, pred, user_data);
2880 if ( matvar ) {
2881 const int err = ReadData(mat, matvar);
2882 if ( err ) {
2883 Mat_VarFree(matvar);
2884 matvar = NULL;
2885 break;
2886 }
2887 } else {
2888 if ( mat->version != MAT_FT_MAT73 ) {
2889 /* Reset the file position */
2890 (void)fseeko((FILE *)mat->fp, fpos, SEEK_SET);
2891 }
2892 break;
2893 }
2894 } while ( (NULL != pred) && 0 == pred(matvar->name, user_data) );
2895 /* for 7.3 the predicate will be called one extra time */
2896
2897 return matvar;
2898 }
2899
2900 /** @brief Writes the given MAT variable to a MAT file
2901 *
2902 * Writes the MAT variable information stored in matvar to the given MAT file.
2903 * The variable will be written to the end of the file.
2904 * @ingroup MAT
2905 * @param mat MAT file to write to
2906 * @param matvar MAT variable information to write
2907 * @retval 1
2908 * @deprecated
2909 * @see Mat_VarWrite/Mat_VarWriteAppend
2910 */
2911 int
2912 Mat_VarWriteInfo(const mat_t *mat, matvar_t *matvar)
2913 {
2914 Mat_Critical(
2915 "Mat_VarWriteInfo/Mat_VarWriteData is not supported. "
2916 "Use %s instead!",
2917 mat->version == MAT_FT_MAT73 ? "Mat_VarWrite/Mat_VarWriteAppend" : "Mat_VarWrite");
2918 return MATIO_E_OPERATION_NOT_SUPPORTED;
2919 }
2920
2921 /** @brief Writes the given data to the MAT variable
2922 *
2923 * Writes data to a MAT variable. The variable must have previously been
2924 * written with Mat_VarWriteInfo.
2925 * @ingroup MAT
2926 * @param mat MAT file to write to
2927 * @param matvar MAT variable information to write
2928 * @param data pointer to the data to write
2929 * @param start array of starting indices
2930 * @param stride stride of data
2931 * @param edge array specifying the number to read in each direction
2932 * @retval 1
2933 * @deprecated
2934 * @see Mat_VarWrite/Mat_VarWriteAppend
2935 */
2936 int
2937 Mat_VarWriteData(const mat_t *mat, matvar_t *matvar, void *data, const int *start,
2938 const int *stride, const int *edge)
2939 {
2940 Mat_Critical(
2941 "Mat_VarWriteInfo/Mat_VarWriteData is not supported. "
2942 "Use %s instead!",
2943 mat->version == MAT_FT_MAT73 ? "Mat_VarWrite/Mat_VarWriteAppend" : "Mat_VarWrite");
2944 return MATIO_E_OPERATION_NOT_SUPPORTED;
2945 }
2946
2947 /** @brief Writes the given MAT variable to a MAT file
2948 *
2949 * Writes the MAT variable information stored in matvar to the given MAT file.
2950 * The variable will be written to the end of the file.
2951 * @ingroup MAT
2952 * @param mat MAT file to write to
2953 * @param matvar MAT variable information to write
2954 * @param compress Whether or not to compress the data
2955 * (Only valid for version 5 and 7.3 MAT files and variables with
2956 numeric data)
2957 * @retval 0 on success
2958 */
2959 int
2960 Mat_VarWrite(mat_t *mat, matvar_t *matvar, enum matio_compression compress)
2961 {
2962 int err;
2963
2964 if ( NULL == mat || NULL == matvar )
2965 return MATIO_E_BAD_ARGUMENT;
2966
2967 if ( NULL == mat->dir ) {
2968 size_t n = 0;
2969 (void)Mat_GetDir(mat, &n);
2970 }
2971
2972 if ( NULL != mat->dir ) {
2973 /* Error if MAT variable already exists in MAT file */
2974 size_t i;
2975 for ( i = 0; i < mat->num_datasets; i++ ) {
2976 if ( NULL != mat->dir[i] && 0 == strcmp(mat->dir[i], matvar->name) ) {
2977 Mat_Critical("Variable %s already exists", matvar->name);
2978 return MATIO_E_OUTPUT_BAD_DATA;
2979 }
2980 }
2981 }
2982
2983 if ( mat->version == MAT_FT_MAT5 )
2984 err = Mat_VarWrite5(mat, matvar, compress);
2985 else if ( mat->version == MAT_FT_MAT73 )
2986 #if defined(MAT73) && MAT73
2987 err = Mat_VarWrite73(mat, matvar, compress);
2988 #else
2989 err = MATIO_E_OPERATION_NOT_SUPPORTED;
2990 #endif
2991 else if ( mat->version == MAT_FT_MAT4 )
2992 err = Mat_VarWrite4(mat, matvar);
2993 else
2994 err = MATIO_E_FAIL_TO_IDENTIFY;
2995
2996 if ( err == MATIO_E_NO_ERROR ) {
2997 /* Update directory */
2998 char **dir;
2999 if ( NULL == mat->dir ) {
3000 dir = (char **)malloc(sizeof(char *));
3001 } else {
3002 dir = (char **)realloc(mat->dir, (mat->num_datasets + 1) * (sizeof(char *)));
3003 }
3004 if ( NULL != dir ) {
3005 mat->dir = dir;
3006 if ( NULL != matvar->name ) {
3007 mat->dir[mat->num_datasets++] = strdup(matvar->name);
3008 } else {
3009 mat->dir[mat->num_datasets++] = NULL;
3010 }
3011 } else {
3012 err = MATIO_E_OUT_OF_MEMORY;
3013 Mat_Critical("Couldn't allocate memory for the directory");
3014 }
3015 }
3016
3017 return err;
3018 }
3019
3020 /** @brief Writes/appends the given MAT variable to a version 7.3 MAT file
3021 *
3022 * Writes the numeric data of the MAT variable stored in matvar to the given
3023 * MAT file. The variable will be written to the end of the file if it does
3024 * not yet exist or appended to the existing variable.
3025 * @ingroup MAT
3026 * @param mat MAT file to write to
3027 * @param matvar MAT variable information to write
3028 * @param compress Whether or not to compress the data
3029 * (Only valid for version 7.3 MAT files and variables with numeric data)
3030 * @param dim dimension to append data
3031 * (Only valid for version 7.3 MAT files and variables with numeric data)
3032 * @retval 0 on success
3033 */
3034 int
3035 Mat_VarWriteAppend(mat_t *mat, matvar_t *matvar, enum matio_compression compress, int dim)
3036 {
3037 int err;
3038
3039 if ( NULL == mat || NULL == matvar )
3040 return MATIO_E_BAD_ARGUMENT;
3041
3042 if ( NULL == mat->dir ) {
3043 size_t n = 0;
3044 (void)Mat_GetDir(mat, &n);
3045 }
3046
3047 if ( mat->version == MAT_FT_MAT73 ) {
3048 #if defined(MAT73) && MAT73
3049 int append = 0;
3050 {
3051 /* Check if MAT variable already exists in MAT file */
3052 size_t i;
3053 for ( i = 0; i < mat->num_datasets; i++ ) {
3054 if ( NULL != mat->dir[i] && 0 == strcmp(mat->dir[i], matvar->name) ) {
3055 append = 1;
3056 break;
3057 }
3058 }
3059 }
3060 err = Mat_VarWriteAppend73(mat, matvar, compress, dim);
3061 if ( err == MATIO_E_NO_ERROR && 0 == append ) {
3062 /* Update directory */
3063 char **dir;
3064 if ( NULL == mat->dir ) {
3065 dir = (char **)malloc(sizeof(char *));
3066 } else {
3067 dir = (char **)realloc(mat->dir, (mat->num_datasets + 1) * (sizeof(char *)));
3068 }
3069 if ( NULL != dir ) {
3070 mat->dir = dir;
3071 if ( NULL != matvar->name ) {
3072 mat->dir[mat->num_datasets++] = strdup(matvar->name);
3073 } else {
3074 mat->dir[mat->num_datasets++] = NULL;
3075 }
3076 } else {
3077 err = MATIO_E_OUT_OF_MEMORY;
3078 Mat_Critical("Couldn't allocate memory for the directory");
3079 }
3080 }
3081 #else
3082 err = MATIO_E_OPERATION_NOT_SUPPORTED;
3083 #endif
3084 } else if ( mat->version == MAT_FT_MAT4 || mat->version == MAT_FT_MAT5 ) {
3085 err = MATIO_E_OPERATION_NOT_SUPPORTED;
3086 } else {
3087 err = MATIO_E_FAIL_TO_IDENTIFY;
3088 }
3089
3090 return err;
3091 }