Repository navigation
Expand file tree
/
Copy pathsavemsgpack.m
More file actions
652 lines (623 loc) · 22.4 KB
/
Copy pathsavemsgpack.m
File metadata and controls
652 lines (623 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
function msgpk = savemsgpack(rootname, obj, varargin)
%
% msgpk = savemsgpack(obj)
% or
% msgpk = savemsgpack(rootname, obj, filename)
% msgpk = savemsgpack(rootname, obj, opt)
% msgpk = savemsgpack(rootname, obj, 'param1', value1, 'param2', value2, ...)
%
% Convert a MATLAB value (numeric, logical, char, cell, struct, containers.Map, and what
% jdataencode encodes: complex, sparse, N-D arrays, tables, ...) to MessagePack (https://msgpack.org)
%
% input:
% rootname: the name of the root (empty: the value alone, not in a one-key map)
% obj: the value
% filename: a file to write (same as the FileName option)
% opt: a struct of options, or ('param', value) pairs:
% FileName ['']: write the bytes to this file
% PackedArray [0|1]: write numeric arrays (vectors, matrices, N-D arrays) as typed N-D
% arrays, the MessagePack extension proposed in
% https://github.com/msgpack/msgpack/pull/267: 0xc1, the type marker
% (0xca-0xd3), the number of dimensions, the dimensions (big-endian
% uint32) and the values (big-endian, row-major, no markers). Compact and
% fast to read and write, but only readers that know it (loadmsgpack, jdai)
% read it; 0 writes standard MessagePack (nested arrays)
% NestArray [0|1]: write N-D arrays as nested arrays (1) instead of JData annotations
% KeepType [0|1]: keep the class of integers (1), or write each array with the
% smallest integer type that holds its values (0, as savebj)
% Compression ['zlib'|'']: as savebj, numeric arrays of more than CompressArraySize
% [300] values are written compressed, as JData annotations (their
% compressed bytes a bin); '' writes them as they are
% PreEncode [1|0]: run jdataencode on the value first (complex, sparse, N-D arrays,
% tables, maps, ... as JData annotations)
% UnpackHex [1|0]: field names decoded with decodevarname (x0x20_ is a space)
% ForceRootName [0|1]: a struct or cell with no root name is written as {"root": ...}
% Backend ['auto'|'mex'|'m']: 'auto' uses the compiled jdai backend (jdai.savemsgpack)
% when it is on the path, else this file's code; 'mex' requires jdai;
% 'm' never uses it
% output:
% msgpk: the MessagePack bytes (a char row, as savebj gives its bytes)
%
% The layout is savebj's, so loadmsgpack reads back what loadbj reads from savebj: a row vector
% is an array, a matrix (also a column vector) an array of its rows, every number of an array
% with one type (the smallest integer type that holds them all, or float32/float64), a logical
% scalar true/false, a logical array its 0/1 values (uint8), a char row a string (UTF-8), a char
% matrix an array of its rows, [] nil, a struct a map (a struct array an array of maps), a cell an
% array, a uint8 row a bin
%
% examples:
% bytes = savemsgpack('', struct('a', [1 2 3], 'b', 'text'));
% data = loadmsgpack(bytes)
% savemsgpack('', rand(100, 100, 3), 'FileName', 'img.msgpack', 'PackedArray', 1);
%
% license:
% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://neurojson.org/jsonlab)
%
if (nargin == 1)
obj = rootname;
rootname = '';
end
if (length(varargin) == 1 && ischar(varargin{1}))
opt = struct('filename', varargin{1});
else
opt = varargin2struct(varargin{:});
end
% the compiled backend (jdai) when it is on the path: the same bytes, much faster; options and values
% it does not handle, and any error, fall back to the code below
backend = lower(jsonopt('Backend', 'auto', opt));
if (~strcmp(backend, 'm') && exist('jdai_mex', 'file') == 3)
try
if (nargout > 0 || isempty(jsonopt('FileName', '', opt)))
msgpk = jdai.savemsgpack(rootname, obj, opt);
else
jdai.savemsgpack(rootname, obj, opt);
end
return
catch err
if (strcmp(backend, 'mex'))
rethrow(err);
end
end
end
o.packed = jsonopt('PackedArray', 0, opt) == 1;
o.keeptype = jsonopt('KeepType', 0, opt) == 1;
o.nestarray = jsonopt('NestArray', 0, opt) == 1;
o.unpackhex = jsonopt('UnpackHex', 1, opt);
o.isoctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
[~, ~, endian] = computer;
o.swap = (endian == 'L'); % MessagePack is big-endian
% savebj's compression: zlib by default, for numeric arrays of more than CompressArraySize values
o.zip = jsonopt('Compression', 'zlib', opt);
o.zipsize = jsonopt('CompressArraySize', 300, opt);
if (~isempty(o.zip))
% (a name, or a list of several codecs: applied from the last to the first)
names = o.zip;
if (ischar(names) || isa(names, 'string'))
names = cellstr(names);
end
names = cellfun(@(m) lower(char(m)), reshape(names, 1, []), 'UniformOutput', false);
if (any(~cellfun(@isempty, regexp(names, '^blosc2', 'once'))))
error('savemsgpack: Compression %s is not supported', strjoin(names, ','));
end
if (any(ismember(names(1:end - 1), {'labelac', 'slabelac'})))
error('labelac and slabelac can only be the first codec applied (the last in the list)');
end
o.zipfun = @(z, varargin) mp_zipchain(z, names, varargin{:});
o.zipname = names;
end
% jdataencode for what MessagePack has no form for (complex, sparse, N-D arrays, tables, other
% classes): on those values only, as they are met (it gives each value what it gives it within
% the whole), or on the whole value first when an option changes ordinary arrays too
o.preencode = jsonopt('PreEncode', 1, opt) == 1;
% (jdataencode compresses the data of what it encodes, complex and sparse arrays, as savebj does:
% with the compression in effect, zlib by default)
fn = fieldnames(opt);
o.jdopt = rmfield(opt, fn(strcmpi(fn, 'Compression') | strcmpi(fn, 'CompressArraySize')));
o.jdopt.Compression = o.zip;
o.jdopt.CompressArraySize = o.zipsize;
if (o.preencode && (jsonopt('UseArrayShape', 0, opt) || jsonopt('ArrayToStruct', 0, opt) || jsonopt('AnnotateArray', 0, opt) || ...
jsonopt('NestArray', 0, opt) || ~isempty(jsonopt('ArrayChunks', [], opt)) || jsonopt('FormatVersion', 4, opt) < 4))
obj = jdataencode(obj, 'Base64', 0, 'UseArrayZipSize', 0, o.jdopt);
end
if (isempty(rootname) && jsonopt('ForceRootName', 0, opt) && (isstruct(obj) || iscell(obj)))
rootname = 'root';
end
if (isempty(rootname))
bytes = mp_value(obj, o);
else
bytes = [uint8(129), mp_str(rootname, o), mp_value(obj, o)]; % {rootname: obj}
end
msgpk = char(bytes);
filename = jsonopt('FileName', '', opt);
if (~isempty(filename))
fid = fopen(filename, 'wb');
fwrite(fid, bytes);
fclose(fid);
end
%% =========================================================================
function b = mp_value(x, o)
% one value's bytes (a uint8 row)
if (isempty(x) && ~isstruct(x) && ~isa(x, 'containers.Map'))
if (ischar(x))
b = uint8(160); % '': an empty string
elseif (iscell(x))
b = uint8(144); % {}: an empty array (savebj writes null)
else
b = uint8(192); % []: nil
end
elseif (ischar(x))
b = mp_char(x, o);
elseif (isnumeric(x) || islogical(x))
if (isscalar(x) && isreal(x) && ~issparse(x))
b = mp_scalar(x, o);
elseif (~isreal(x) || issparse(x) || (ndims(x) > 2 && ~o.packed && ~o.nestarray && (isempty(o.zip) || numel(x) <= o.zipsize)))
b = mp_encoded(x, o); % JData annotations (an N-D array compressed or packed: below)
else
b = mp_numeric(x, o);
end
elseif (isstruct(x))
b = mp_struct(x, o);
elseif (iscell(x))
b = mp_cell(x, o);
elseif (isa(x, 'containers.Map'))
b = mp_map(x, o);
elseif (isa(x, 'string'))
b = mp_value(char(x), o);
else
b = mp_encoded(x, o);
end
%% =========================================================================
function b = mp_encoded(x, o)
% a value MessagePack has no form for, as jdataencode encodes it
if (~o.preencode)
error('savemsgpack:type', 'savemsgpack: a %s cannot be written without PreEncode', class(x));
end
y = jdataencode(x, 'Base64', 0, 'UseArrayZipSize', 0, o.jdopt);
if (strcmp(class(y), class(x)) && isequaln(size(y), size(x)) && ~isstruct(y))
if ((isnumeric(x) || islogical(x)) && isreal(x))
b = mp_numeric(full(x), o); % left as it is (NestArray): nested arrays
return
end
error('savemsgpack:type', 'savemsgpack: a %s cannot be written', class(x));
end
o.preencode = false; % (what it gives needs no more encoding)
b = mp_value(y, o);
%% =========================================================================
function b = mp_scalar(x, o)
% one real number: a fixint when it fits (as uint8 or int8 read back), else the smallest type
if (islogical(x))
b = uint8(194 + x); % false / true
return
end
d = double(x);
if (d == fix(d) && ~o.keeptype && abs(d) < 9007199254740992)
if (d >= 0 && d < 128)
b = uint8(d); % a positive fixint
return
elseif (d < 0 && d >= -32)
b = uint8(256 + d); % a negative fixint
return
end
end
if (d == fix(d) && ~o.keeptype && abs(d) < 9007199254740992)
% the smallest integer type (as mp_type chooses), without its general search
if (d >= 0)
if (d < 256)
b = uint8([204, d]);
return
elseif (d < 65536)
b = uint8([205, floor(d / 256), mod(d, 256)]);
return
elseif (d < 4294967296)
b = uint8([206, mod(floor(d ./ [16777216, 65536, 256, 1]), 256)]);
return
end
elseif (d >= -128)
b = uint8([208, d + 256]);
return
end
end
[cls, mk] = mp_type(x, o);
raw = typecast(cast(x, cls), 'uint8');
if (o.swap)
raw = raw(end:-1:1);
end
b = [uint8(mk), raw];
%% =========================================================================
function b = mp_header(n, fix, base16, maxfix)
% an array (fix 0x90, 0xdc/0xdd), map (0x80, 0xde/0xdf) or string (0xa0, 0xd9-0xdb) length
if (n <= maxfix)
b = uint8(fix + n);
elseif (n < 65536)
b = [uint8(base16), uint8([floor(n / 256), mod(n, 256)])];
else
b = [uint8(base16 + 1), uint8(mod(floor(n ./ [16777216, 65536, 256, 1]), 256))];
end
%% =========================================================================
function b = mp_str(s, o)
% a string: its UTF-8 bytes (Octave's char holds them; MATLAB's is UTF-16)
if (~o.isoctave && any(s > 127))
u = unicode2native(s, 'UTF-8');
else
u = uint8(s);
end
n = length(u);
if (n < 32)
b = [uint8(160 + n), u];
elseif (n < 256)
b = [uint8([217, n]), u];
else
b = [mp_header(n, 0, 218, -1), u];
end
%% =========================================================================
function b = mp_char(x, o)
% a char row: a string; a char matrix: an array of its rows
if (size(x, 1) <= 1 && ismatrix(x))
b = mp_str(x, o);
return
end
x = reshape(x, size(x, 1), []);
parts = cell(1, size(x, 1) + 1);
parts{1} = mp_header(size(x, 1), 144, 220, 15);
for k = 1:size(x, 1)
parts{k + 1} = mp_str(x(k, :), o);
end
b = [parts{:}];
%% =========================================================================
function [cls, mk] = mp_type(x, o)
% the one type an array's numbers are written with: savebj's choice (the smallest integer type
% that holds them all, unless KeepType; float32/float64 otherwise) and its marker
if (islogical(x))
cls = 'uint8';
elseif (isinteger(x) && o.keeptype)
cls = class(x);
elseif (isfloat(x) && (o.keeptype || ~isreal(x) || any(x(:) ~= fix(x(:))) || any(~isfinite(x(:)))))
cls = '';
else
mn = double(min(x(:)));
mx = double(max(x(:)));
if (mn >= 0)
lim = [255, 65535, 4294967295, 18446744073709551615];
names = {'uint8', 'uint16', 'uint32', 'uint64'};
k = find(mx <= lim, 1);
else
names = {'int8', 'int16', 'int32', 'int64'};
k = find(mn >= -[128, 32768, 2147483648, 9223372036854775808] & mx <= [127, 32767, 2147483647, 9223372036854775807], 1);
end
if (isempty(k))
cls = ''; % beyond 64 bits: a float
else
cls = names{k};
end
end
if (isempty(cls))
if (isa(x, 'single'))
cls = 'single';
else
cls = 'double';
end
end
mk = mp_marker(cls);
%% =========================================================================
function mk = mp_marker(cls)
switch (cls)
case 'single'
mk = 202;
case 'double'
mk = 203;
case 'uint8'
mk = 204;
case 'uint16'
mk = 205;
case 'uint32'
mk = 206;
case 'uint64'
mk = 207;
case 'int8'
mk = 208;
case 'int16'
mk = 209;
case 'int32'
mk = 210;
case 'int64'
mk = 211;
otherwise
mk = 203;
end
%% =========================================================================
function [b, w] = mp_numbers(v, cls, mk, o)
% numbers (a row, row-major) written with one type: w bytes each (fixints when they are uint8
% below 128, so they read back as uint8)
v = cast(v(:)', cls);
if (strcmp(cls, 'uint8') && all(v < 128))
b = v;
w = 1;
return
end
raw = typecast(v, 'uint8');
n = length(raw) / length(v);
raw = reshape(raw, n, []);
if (o.swap && n > 1)
raw = raw(n:-1:1, :);
end
b = [repmat(uint8(mk), 1, length(v)); raw];
b = b(:)';
w = n + 1;
%% =========================================================================
function b = mp_numeric(x, o)
% a number, or an array of them
if (~isreal(x))
error('savemsgpack:type', 'savemsgpack: complex numbers are written as JData annotations (PreEncode)');
end
if (issparse(x))
x = full(x);
end
if (isscalar(x))
if (islogical(x))
b = uint8(194 + x); % false / true
return
end
[cls, mk] = mp_type(x, o);
if (strcmp(cls, 'int8') && x >= -32)
b = typecast(int8(x), 'uint8'); % a negative fixint
else
b = mp_numbers(x, cls, mk, o);
end
return
end
if (isa(x, 'uint8') && isrow(x) && ~o.packed)
% a uint8 row: a bin (it reads back as a uint8 row); bin8, or bin16/32
if (length(x) < 256)
b = [uint8([196, length(x)]), x];
else
b = [mp_header(length(x), 0, 197, -1), x];
end
return
end
if (~isempty(o.zip) && numel(x) > o.zipsize)
b = mp_zipped(x, o);
return
end
[cls, mk] = mp_type(x, o);
if (o.packed)
if (ndims(x) > 2)
% an N-D array keeps its class (as savebj's _ArrayType_ annotation does)
cls = class(x);
if (islogical(x))
cls = 'uint8';
end
mk = mp_marker(cls);
end
b = mp_packed(x, size(x), cls, mk, o);
return
end
if (isrow(x))
[nums, ~] = mp_numbers(x, cls, mk, o);
b = [mp_header(numel(x), 144, 220, 15), nums];
return
end
% a matrix (or N-D array): arrays of rows, row-major, nested
dims = size(x);
v = permute(x, ndims(x):-1:1);
[nums, w] = mp_numbers(v(:)', cls, mk, o);
b = mp_nest(nums, w, dims);
%% =========================================================================
function b = mp_zipped(x, o)
% a compressed array, as savebj writes it: a JData annotation with the compressed row-major bytes
% (in the array's class; logical as uint8) as a bin
if (islogical(x))
data = uint8(permute(x, ndims(x):-1:1));
else
data = permute(x, ndims(x):-1:1);
end
if (ismember(o.zipname{end}, {'labelac', 'slabelac'}))
% labels: the element size and the two fastest dimensions (data is row-major now)
z = o.zipfun(typecast(data(:)', 'uint8'), numel(typecast(cast(0, class(data)), 'uint8')), size(data, 1), size(data, 2));
else
z = o.zipfun(typecast(data(:)', 'uint8'));
end
z = uint8(z(:)');
o.zip = ''; % (its small arrays are not compressed again)
b = [uint8(133), mp_str('_ArrayType_', o), mp_str(class(x), o), ...
mp_str('_ArraySize_', o), mp_numeric(size(x), o), ...
mp_str('_ArrayZipSize_', o), mp_numeric([1, numel(x)], o), ...
mp_str('_ArrayZipType_', o), mp_ziptype(o.zipname, o), ...
mp_str('_ArrayZipData_', o), mp_numeric(z, setfield(o, 'packed', false))];
%% =========================================================================
function b = mp_ziptype(names, o)
% _ArrayZipType_: the codec's name, or the array of several
if (numel(names) == 1)
b = mp_str(names{1}, o);
return
end
b = mp_header(numel(names), 144, 220, 15);
for k = 1:numel(names)
b = [b, mp_str(names{k}, o)]; %#ok<AGROW>
end
%% =========================================================================
function z = mp_zipchain(z, names, varargin)
% bytes through the codecs, from the last in the list to the first (varargin: a label codec's
% arguments, when it is the last)
z = reshape(uint8(z), 1, []);
for k = numel(names):-1:1
if (k == numel(names))
z = feval([names{k} 'encode'], z, varargin{:});
else
z = feval([names{k} 'encode'], z);
end
z = reshape(uint8(z), 1, []);
end
%% =========================================================================
function b = mp_nest(nums, w, dims)
% numbers (w bytes each, row-major) as nested arrays of the given dimensions
if (length(dims) == 1)
b = [mp_header(dims(1), 144, 220, 15), nums];
return
end
inner = prod(dims(2:end));
if (length(dims) == 2)
% the rows at once: a header before each
h = mp_header(dims(2), 144, 220, 15);
rows = reshape(nums, w * dims(2), dims(1));
rows = [repmat(h(:), 1, dims(1)); rows];
b = [mp_header(dims(1), 144, 220, 15), rows(:)'];
return
end
parts = cell(1, dims(1) + 1);
parts{1} = mp_header(dims(1), 144, 220, 15);
for k = 1:dims(1)
parts{k + 1} = mp_nest(nums((k - 1) * inner * w + 1:k * inner * w), w, dims(2:end));
end
b = [parts{:}];
%% =========================================================================
function b = mp_packed(x, dims, cls, mk, o)
% a typed N-D array (msgpack PR 267): 0xc1, the type, D, D big-endian uint32 dimensions, the
% values big-endian and row-major with no markers; a row vector is 1-D
if (length(dims) == 2 && dims(1) == 1)
dims = dims(2);
end
v = cast(permute(x, ndims(x):-1:1), cls);
raw = typecast(v(:)', 'uint8');
n = mp_bytes(cls);
if (o.swap && n > 1)
raw = reshape(raw, n, []);
raw = raw(n:-1:1, :);
raw = raw(:)';
end
d = uint8(mod(floor(bsxfun(@rdivide, dims(:), [16777216, 65536, 256, 1])), 256))';
b = [uint8([193, mk, length(dims)]), d(:)', raw];
%% =========================================================================
function n = mp_bytes(cls)
switch (cls)
case {'uint8', 'int8'}
n = 1;
case {'uint16', 'int16'}
n = 2;
case {'uint32', 'int32', 'single'}
n = 4;
otherwise
n = 8;
end
%% =========================================================================
function b = mp_struct(x, o)
% a struct: a map; a struct array: an array of maps (columns of rows, as savebj); an N-D array
% data annotation (_ArrayType_, _ArraySize_, _ArrayData_) with PackedArray: a typed N-D array
if (numel(x) == 1)
names = fieldnames(x);
if (any(strcmp(names, '_ArrayType_')) || any(strcmp(names, 'x0x5F_ArrayType_')))
o.zip = ''; % a JData annotation: its arrays as they are
end
if (o.packed && length(names) == 3)
b = mp_annotated(x, names, o);
if (~isempty(b))
return
end
end
parts = cell(1, 2 * length(names) + 1);
parts{1} = mp_header(length(names), 128, 222, 15);
for k = 1:length(names)
nm = names{k};
if (o.unpackhex && ~isempty(strfind(nm, '0x')))
nm = decodevarname(nm, o.unpackhex);
end
parts{2 * k} = mp_str(nm, o);
parts{2 * k + 1} = mp_value(x.(names{k}), o);
end
b = [parts{:}];
return
end
if (isempty(x))
b = uint8(144); % an empty struct array: an empty array
return
end
dim = size(x);
if (ndims(x) > 2)
x = reshape(x, dim(1), []);
dim = size(x);
end
parts = cell(1, numel(x) + dim(2) + 1);
np = 1;
parts{1} = mp_header(dim(2), 144, 220, 15);
for j = 1:dim(2)
if (dim(1) > 1)
np = np + 1;
parts{np} = mp_header(dim(1), 144, 220, 15);
end
for i = 1:dim(1)
np = np + 1;
parts{np} = mp_struct(x(i, j), o);
end
end
b = [parts{1:np}];
%% =========================================================================
function b = mp_annotated(x, names, o)
% a plain N-D array annotation as a typed N-D array (its class, its dimensions), or [] if not one
b = [];
dn = cellfun(@(n) decodevarname(n), names, 'UniformOutput', false);
if (~all(ismember({'_ArrayType_', '_ArraySize_', '_ArrayData_'}, dn)))
return
end
cls = x.(names{strcmp(dn, '_ArrayType_')});
dims = double(x.(names{strcmp(dn, '_ArraySize_')}));
data = x.(names{strcmp(dn, '_ArrayData_')});
if (~ischar(cls) || ~(isnumeric(data) || islogical(data)) || ~isreal(data) || numel(data) ~= prod(dims) || ...
~any(strcmp(cls, {'double', 'single', 'uint8', 'int8', 'uint16', 'int16', 'uint32', 'int32', 'uint64', 'int64', 'logical'})))
return
end
if (strcmp(cls, 'logical'))
cls = 'uint8';
end
% _ArrayData_ is row-major already: written as it is, with the annotation's dimensions
v = cast(data(:)', cls);
raw = typecast(v, 'uint8');
n = mp_bytes(cls);
if (o.swap && n > 1)
raw = reshape(raw, n, []);
raw = raw(n:-1:1, :);
raw = raw(:)';
end
d = uint8(mod(floor(bsxfun(@rdivide, dims(:), [16777216, 65536, 256, 1])), 256))';
b = [uint8([193, mp_marker(cls), length(dims)]), d(:)', raw];
%% =========================================================================
function b = mp_cell(x, o)
% a cell: an array (a matrix: its rows, row-major, as savebj)
if (~isvector(x))
x = permute(x, ndims(x):-1:1);
end
dim = size(x);
if (ndims(x) > 2)
x = reshape(x, dim(1), []);
dim = size(x);
end
parts = cell(1, numel(x) + dim(2) + 1);
np = 1;
parts{1} = mp_header(dim(2), 144, 220, 15);
for j = 1:dim(2)
if (dim(1) > 1)
np = np + 1;
parts{np} = mp_header(dim(1), 144, 220, 15);
end
for i = 1:dim(1)
np = np + 1;
parts{np} = mp_value(x{i, j}, o);
end
end
b = [parts{1:np}];
%% =========================================================================
function b = mp_map(x, o)
% a containers.Map: a map
ks = keys(x);
vs = values(x);
parts = cell(1, 2 * length(ks) + 1);
parts{1} = mp_header(length(ks), 128, 222, 15);
for k = 1:length(ks)
key = ks{k};
if (~ischar(key))
key = sprintf('%.17g', key);
end
parts{2 * k} = mp_str(key, o);
parts{2 * k + 1} = mp_value(vs{k}, o);
end
b = [parts{:}];