dmio 0.1.2

A shared library providing functionality to read, write and modify files saved in the DigitalMicrograph file format (version 3 or 4)
Documentation
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
/*
 * Copyright 2018 Christian Ebner
 *
 * This file is part of dmio.
 *
 * dmio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dmio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dmio.  If not, see <http://www.gnu.org/licenses/>.
 */

use std::io::Write;
use std::fs::File;
use std::mem;
use byteorder::{ByteOrder, BigEndian, LittleEndian, WriteBytesExt};

use super::DMImage;
use super::dmtypes::*;
use super::taggroup_entries::{Key, Tag, TagGroup};
use super::taggroup_entries::Key::*;
use super::taggroup_entries::Tag::*;
use Result;

pub trait DMImageWriteByVersion {
    fn write_by_version(dmwriter: &mut DMImageWriter, val: usize) -> Result<usize>;
    fn write_by_version_to_buffer(buffer: &mut Vec<u8>, val: usize) -> Result<usize>;
    fn write_header(dmwriter: &mut DMImageWriter) -> Result<usize>;
    fn write_taggroup_size(dmwriter: &mut DMImageWriter, val: usize) -> Result<usize>;
}

/// The `DMImageWriter` provides functionality to binary encode a `DMImage` into a byte buffer.
pub struct DMImageWriter<'a> {
    buffer: Vec<u8>,
    image: &'a DMImage,
}

impl DMImageWriteByVersion for DM3Writer {
    #[inline]
    fn write_by_version(dmwriter: &mut DMImageWriter, val: usize) -> Result<usize> {
        debug!("DM3::write_by_version()");
        dmwriter.buffer.write_u32::<BigEndian>(val as u32)?;
        let bytes = 4;
        debug!("DM3::write_by_version() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_header(dmwriter: &mut DMImageWriter) -> Result<usize> {
        debug!("DM3::write_header()");
        dmwriter.buffer.write_u32::<BigEndian>(3)?;
        let tg_size = dmwriter.image.tg_size;
        dmwriter.buffer.write_u32::<BigEndian>(tg_size as u32)?;
        let bigendian = if dmwriter.image.bigendian {
            BIG_ENDIAN
        } else {
            LITTLE_ENDIAN
        };
        dmwriter.buffer.write_u32::<BigEndian>(bigendian as u32)?;
        let bytes = 12;
        debug!("DM3::write_header() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_by_version_to_buffer(buffer: &mut Vec<u8>, t: usize) -> Result<usize> {
        debug!("DM3:write_by_version_to_buffer()");
        buffer.write_u32::<BigEndian>(D_ZERO as u32)?;
        buffer.write_u32::<BigEndian>(t as u32)?;
        let bytes = 8;
        debug!("DM3:write_by_version_to_buffer() -> {} bytes written", bytes);

        Ok(bytes)
    }

    // DM3 doesn't have the TagGroup size field, so simply do notting
    #[inline]
    fn write_taggroup_size(_dmwriter: &mut DMImageWriter, _size: usize) -> Result<usize> {
        Ok(0)
    }
}

impl DMImageWriteByVersion for DM4Writer {
    fn write_by_version(dmwriter: &mut DMImageWriter, val: usize) -> Result<usize> {
        debug!("DM4::write_by_version()");
        dmwriter.buffer.write_u32::<BigEndian>(val as u32)?;
        let bytes = 8;
        debug!("DM4::write_by_version() -> {} bytes written", bytes);

        Ok(bytes)
    }

    fn write_header(dmwriter: &mut DMImageWriter) -> Result<usize> {
        debug!("DM4::write_header()");
        dmwriter.buffer.write_u32::<BigEndian>(4)?;
        let tg_size = dmwriter.image.tg_size;
        dmwriter.buffer.write_u64::<BigEndian>(tg_size as u64)?;
        let bigendian = if dmwriter.image.bigendian {
            BIG_ENDIAN
        } else {
            LITTLE_ENDIAN
        };
        dmwriter.buffer.write_u32::<BigEndian>(bigendian as u32)?;
        let bytes =16;
        debug!("DM4::write_header() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_by_version_to_buffer(buffer: &mut Vec<u8>, t: usize) -> Result<usize> {
        debug!("DM4:write_by_version_to_buffer()");
        buffer.write_u64::<BigEndian>(D_ZERO as u64)?;
        buffer.write_u64::<BigEndian>(t as u64)?;
        let bytes = 16;
        debug!("DM4:write_by_version_to_buffer() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_taggroup_size(dmwriter: &mut DMImageWriter, size: usize) -> Result<usize> {
        dmwriter.buffer.write_u64::<BigEndian>(size as u64)?;

        Ok(8)
    }
}

impl<'a> DMImageWriter<'a> {
    pub fn new(image: &'a DMImage) -> DMImageWriter<'a> {
        DMImageWriter {
            buffer: Vec::new(),
            image,
        }
    }

    pub fn from(image: &'a DMImage) -> DMImageWriter<'a> {
        DMImageWriter {
            buffer: Vec::with_capacity(image.tg_size + 16),
            image,
        }
    }

    pub fn write_to_file<R: DMImageWriteByVersion>(&mut self, mut file: File) -> Result<()> {
        debug!("DMImageWriter::write_to_file()");
        let buffer = self.serialize::<R>()?;
        debug!("DMImageWriter::write_to_file() -> serialization completed");
        file.write_all(&buffer[..])?;
        debug!("DMImageWriter::write_to_file() -> file written, {} bytes total", buffer.len());

        Ok(())
    }

    pub fn serialize<R: DMImageWriteByVersion>(&mut self) -> Result<Vec<u8>> {
        debug!("DMImageWriter::serialize()");
        let mut bytes = 0;
        bytes += R::write_header(self)?;
        if self.image.bigendian {
            bytes += self.write_taggroup::<R, BigEndian>(&self.image.root)?;
        } else {
            bytes += self.write_taggroup::<R, LittleEndian>(&self.image.root)?;
        }

        // file ends with 8 zero bytes
        self.buffer.append(&mut vec![0u8; 8]);
        bytes += 8;
        // Update the root tg size in the header section, neglecting magic number,
        // the tg_size and the 8 zero bytes at the ending (making 16 bytes in total)
        let final_file_size = self.buffer.len() - 16;
        BigEndian::write_u32(&mut self.buffer[4..8], final_file_size as u32);

        debug!("DMImageWriter::serialize() -> file size {}, total bytes {}", final_file_size, bytes);

        // Switch pointer to buffer to a new, empty one to get ownership
        // of the buffer and be able to return it
        let new_buffer= Vec::new();
        let buffer = mem::replace(&mut self.buffer, new_buffer);

        Ok(buffer)
    }

    #[inline]
    fn write_taggroup<R: DMImageWriteByVersion, T: ByteOrder>(&mut self, tg: &TagGroup) -> Result<usize> {
        debug!("DMImageWriter::write_taggroup()");
        self.buffer.write_u8(
            if tg.sorted() { B_TRUE } else { B_FALSE },
        )?;
        self.buffer.write_u8(
            if tg.opened() { B_TRUE } else { B_FALSE },
        )?;
        let mut bytes = 2;
        bytes += R::write_by_version(self, tg.len())?;

        // Read the individual tag entries of the TagGroup and write them to file
        for (key, tag) in tg.iter() {
            bytes += self.write_tag_entry::<R, T>(key, tag)?;
        }
        debug!("DMImageWriter::write_taggroup() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_tag_entry<R: DMImageWriteByVersion, T: ByteOrder>(&mut self, key: &Key, tag: &Tag) -> Result<usize> {
        debug!("DMImageWriter::write_tag_entry()");
        let mut bytes = 0;
        let label = match *key {
            Label(ref string) => string.clone(),
            Index(_) => String::from(""),
        };

        match *tag {
            TagGroupEntry(ref tg) => {
                self.buffer.write_u8(T_GROUP)?;
                self.buffer.write_u16::<BigEndian>(label.len() as u16)?;
                bytes += 3 + label.len();
                self.buffer.append(&mut label.into_bytes());
                bytes += R::write_taggroup_size(self, 0)?; // TODO replace this with actual size
                bytes += self.write_taggroup::<R, T>(tg)?;
            }
            _ => {
                self.buffer.write_u8(T_TAG)?;
                self.buffer.write_u16::<BigEndian>(label.len() as u16)?;
                bytes += 3 + label.len();
                self.buffer.append(&mut label.into_bytes());
                bytes += R::write_taggroup_size(self, 0)?; // TODO replace this with actual size
                bytes += self.write_tag::<R, T>(tag)?;
            }
        }
        debug!("DMImageWriter::write_tag_entry() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_tag<R: DMImageWriteByVersion, T: ByteOrder>(&mut self, val: &Tag) -> Result<usize> {
        debug!("DMImageWriter::write_tag()");
        // TagTypes consist of a 4 bytes for spacer '%%%%', 4 bytes n = length of definition of
        // encoded type (simple type = 1, string = 2, array = 3, structs 1+2*f with f= number of
        // struct fields), 4*n bytes where n = number of encoded types from before; each 4 bytes
        // define type by ID, finally the data as definde in the TagType

        self.buffer.append(&mut String::from("%%%%").into_bytes());
        let mut bytes = 4;

        match *val {
            Empty => return Err(From::from("TagEntry has type Empty! Cannot write")),
            Short(val) => { 
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_SHORT)?;
                self.buffer.write_i16::<T>(val)?;
                bytes += 2;
            }
            Long(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_LONG)?;
                self.buffer.write_i32::<T>(val)?;
                bytes += 4;
            }
            UShort(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_USHORT)?;
                self.buffer.write_u16::<T>(val)?;
                bytes += 2;
            }
            ULong(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_ULONG)?;
                self.buffer.write_u32::<T>(val)?;
                bytes += 4;
            }
            Float(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_FLOAT)?;
                self.buffer.write_f32::<T>(val)?;
                bytes += 4;
            }
            Double(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_DOUBLE)?;
                self.buffer.write_f64::<T>(val)?;
                bytes += 8;
            }
            Boolean(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_BOOLEAN)?;
                self.buffer.push(if val { B_TRUE } else { B_FALSE });
                bytes += 1;
            }
            Char(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_CHAR)?;
                self.buffer.push(val as u8);
                bytes += 1;
            }
            Octet(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_OCTET)?;
                self.buffer.push(val);
                bytes += 1;
            }
            ULongLong(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_ULONGLONG)?;
                self.buffer.write_u64::<T>(val)?;
                bytes += 8;
            }
            Unknown64(val) => {
                bytes += R::write_by_version(self, T_SIMPLE)?;
                bytes += R::write_by_version(self, D_UNKNOWN64)?;
                self.buffer.write_u64::<T>(val)?;
                bytes += 8;
            }
            CharSeq(ref val) => {
                bytes += R::write_by_version(self, T_STRING)?;
                bytes += R::write_by_version(self, D_STRING)?;
                let mut string = val.clone().into_bytes();
                bytes += R::write_by_version(self, string.len())?;
                bytes += string.len();
                self.buffer.append(&mut string);
            }
            ArrayShort(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_SHORT)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_i16::<T>(*elem)?;
                    bytes += 2;
                }
            }
            ArrayLong(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_LONG)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_i32::<T>(*elem)?;
                    bytes += 4;
                }
            }
            ArrayUShort(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_USHORT)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_u16::<T>(*elem)?;
                    bytes += 2;
                }
            }
            ArrayULong(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_ULONG)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_u32::<T>(*elem)?;
                    bytes += 4;
                }
            }
            ArrayFloat(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_FLOAT)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_f32::<T>(*elem)?;
                    bytes += 4;
                }
            }
            ArrayDouble(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_DOUBLE)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_f64::<T>(*elem)?;
                    bytes += 8;
                }
            }
            ArrayBoolean(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_BOOLEAN)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.push(if *elem { B_TRUE } else { B_FALSE });
                    bytes += 1;
                }
            }
            ArrayChar(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_CHAR)?;
                bytes += R::write_by_version(self, arr.len())?;
                self.buffer.append(&mut arr.clone().into_bytes());
                bytes += arr.len();
            }
            ArrayOctet(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_OCTET)?;
                bytes += R::write_by_version(self, arr.len())?;
                self.buffer.append(&mut arr.clone());
                bytes += arr.len();
            }
            ArrayULongLong(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_ULONGLONG)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_u64::<T>(*elem)?;
                    bytes += 8;
                }
            }
            ArrayUnknown64(ref arr) => {
                bytes += R::write_by_version(self, T_ARRAY)?;
                bytes += R::write_by_version(self, D_ARRAY)?;
                bytes += R::write_by_version(self, D_UNKNOWN64)?;
                bytes += R::write_by_version(self, arr.len())?;
                for elem in arr.iter() {
                    self.buffer.write_u64::<T>(*elem)?;
                    bytes += 8;
                }
            }
            Struct(ref arr) => {
                bytes += self.write_struct::<R, T>(arr)?;
            }
            ComplexArray(ref arr) => {
                bytes += self.write_complex_array::<R, T>(arr)?;
            }
            _ => return Err(From::from("Did not expect this type, corrupt data")),
        }
        debug!("DMImageWriter::write_tag() -> {} bytes written", bytes);

        Ok(bytes)
    }

    #[inline]
    fn write_struct<R: DMImageWriteByVersion, T: ByteOrder>(&mut self, struct_tg: &[Tag]) -> Result<usize> {
        debug!("DMImageWriter::write_struct()");
        let mut bytes = 0;
        let number_fields = struct_tg.len();
        let info_size = 2 * number_fields + 4;
        bytes += R::write_by_version(self, info_size - 1)?;
        bytes += R::write_by_version(self, D_STRUCT)?;
        bytes += R::write_by_version(self, D_ZERO)?;
        bytes += R::write_by_version(self, number_fields)?;

        // TODO find out which capacity to expect and create by Vec::with_capacity()
        let mut data_buf = Vec::new();
        for val in struct_tg.iter() {
            match *val {
                Short(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_SHORT)?;
                    data_buf.write_i16::<T>(val)?;
                }
                Long(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_LONG)?;
                    data_buf.write_i32::<T>(val)?;
                }
                UShort(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_USHORT)?;
                    data_buf.write_u16::<T>(val)?;
                }
                ULong(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_ULONG)?;
                    data_buf.write_u32::<T>(val)?;
                }
                Float(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_FLOAT)?;
                    data_buf.write_f32::<T>(val)?;
                }
                Double(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_DOUBLE)?;
                    data_buf.write_f64::<T>(val)?;
                }
                Boolean(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_BOOLEAN)?;
                    data_buf.push(if val { B_TRUE } else { B_FALSE });
                }
                Char(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_CHAR)?;
                    data_buf.push(val as u8);
                }
                Octet(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_OCTET)?;
                    data_buf.push(val);
                }
                ULongLong(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_ULONGLONG)?;
                    data_buf.write_u64::<T>(val)?;
                }
                Unknown64(val) => {
                    bytes += R::write_by_version(self, D_ZERO)?;
                    bytes += R::write_by_version(self, D_UNKNOWN64)?;
                    data_buf.write_u64::<T>(val)?;
                }
                _ => return Err(From::from("Write struct: Unexpected data type in struct!")),
            }
        }
        self.buffer.append(&mut data_buf);
        bytes += data_buf.len();
        debug!("DMImageWriter::write_struct() -> {} bytes written", bytes);

        Ok(bytes)
    }

    // TODO maybe this can be refactored to be more visually appealing and readable code
    #[inline]
    fn write_complex_array<R: DMImageWriteByVersion, T: ByteOrder>(&mut self, array: &[Tag]) -> Result<usize> {
        debug!("DMImageWriter::write_complex_array()");
        let info_size = match self.image.version {
            DM3 => 4 * 4, // 4 * 4 bytes
            DM4 => 4 * 8, // 4 * 8 bytes
            _ => return Err(From::from("Unknown DMImage version, cannot write...")),
        };
        let mut info_buf = vec![0u8; info_size];

        match self.image.version {
            DM3 => {
                BigEndian::write_u32(&mut info_buf[4..8], D_ARRAY as u32);
                BigEndian::write_u32(&mut info_buf[8..12], D_STRUCT as u32);
                BigEndian::write_u32(&mut info_buf[12..16], D_ZERO as u32);
            },
            DM4 => {
                BigEndian::write_u64(&mut info_buf[8..16], D_ARRAY as u64);
                BigEndian::write_u64(&mut info_buf[16..24], D_STRUCT as u64);
                BigEndian::write_u64(&mut info_buf[24..32], D_ZERO as u64);
            },
            _ => return Err(From::from("Unknown DMImage version, cannot write...")),
        }
        let mut struct_elements = 0usize;
        let mut type_buf = Vec::new();

        let mut data_buf = Vec::new();
        for arr_elem in array.iter() {
            match *arr_elem {
                Struct(ref arr_str) => {
                    struct_elements = arr_str.len();
                    type_buf = Vec::new();
                    for elem in arr_str.iter() {
                        match *elem {
                            Short(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_SHORT)?;
                                data_buf.write_i16::<T>(val)?;
                            }
                            Long(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_LONG)?;
                                data_buf.write_i32::<T>(val)?;
                            }
                            UShort(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_USHORT)?;
                                data_buf.write_u16::<T>(val)?;
                            }
                            ULong(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_ULONG)?;
                                data_buf.write_u32::<T>(val)?;
                            }
                            Float(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_FLOAT)?;
                                data_buf.write_f32::<T>(val)?;
                            }
                            Double(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_DOUBLE)?;
                                data_buf.write_f64::<T>(val)?;
                            }
                            Boolean(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_BOOLEAN)?;
                                data_buf.push(if val { B_TRUE } else { B_FALSE });
                            }
                            Char(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_CHAR)?;
                                data_buf.push(val as u8);
                            }
                            Octet(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_OCTET)?;
                                data_buf.push(val);
                            }
                            ULongLong(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_ULONGLONG)?;
                                data_buf.write_u64::<T>(val)?;
                            }
                            Unknown64(val) => {
                                R::write_by_version_to_buffer(&mut type_buf, D_UNKNOWN64)?;
                                data_buf.write_u64::<T>(val)?;
                            }
                            _ => return Err(From::from("Unknown data type for complex array")),
                        }
                    }
                }
                _ => {
                    return Err(From::from(
                        "Expected a Tag::Struct inside the Tag::ComplexArray",
                    ))
                }
            }
        }
        // write how big the info_buffer truly is
        match self.image.version {
            DM3 => BigEndian::write_u32(&mut info_buf[0..4], 5u32 + struct_elements as u32 * 2u32),
            DM4 => BigEndian::write_u64(&mut info_buf[0..8], 5u64 + struct_elements as u64 * 2u64),
            _ => return Err(From::from("Unknown DMImage version, cannot write...")),
        }
        let mut bytes = 0;
        self.buffer.append(&mut info_buf);
        bytes += info_buf.len();
        bytes += R::write_by_version(self, struct_elements)?;
        self.buffer.append(&mut type_buf);
        bytes += type_buf.len();
        bytes += R::write_by_version(self, array.len())?;
        self.buffer.append(&mut data_buf);
        bytes += data_buf.len();
        debug!("DMImageWriter::write_complex_array() -> {} bytes written", bytes);

        Ok(bytes)
    }
}