File: vtkXMLDataParser.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg1-12
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 125,776 kB
  • sloc: cpp: 1,539,582; ansic: 106,521; python: 78,038; tcl: 47,013; xml: 8,142; yacc: 5,040; java: 4,439; perl: 3,132; lex: 1,926; sh: 1,500; makefile: 122; objc: 83
file content (1131 lines) | stat: -rw-r--r-- 33,202 bytes parent folder | download | duplicates (3)
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLDataParser.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLDataParser.h"

#include "vtkBase64InputStream.h"
#include "vtkByteSwap.h"
#include "vtkCommand.h"
#include "vtkDataCompressor.h"
#include "vtkInputStream.h"
#include "vtkObjectFactory.h"
#include "vtkXMLDataElement.h"
#define vtkXMLDataHeaderPrivate_DoNotInclude
#include "vtkXMLDataHeaderPrivate.h"
#undef vtkXMLDataHeaderPrivate_DoNotInclude

#include <memory>
#include <sstream>

#include "vtkXMLUtilities.h"


vtkStandardNewMacro(vtkXMLDataParser);
vtkCxxSetObjectMacro(vtkXMLDataParser, Compressor, vtkDataCompressor);

//----------------------------------------------------------------------------
vtkXMLDataParser::vtkXMLDataParser()
{
  this->NumberOfOpenElements = 0;
  this->OpenElementsSize = 10;
  this->OpenElements = new vtkXMLDataElement*[this->OpenElementsSize];
  this->RootElement = 0;
  this->AppendedDataPosition = 0;
  this->AppendedDataMatched = 0;
  this->DataStream = 0;
  this->InlineDataStream = vtkBase64InputStream::New();
  this->AppendedDataStream = vtkBase64InputStream::New();

  this->BlockCompressedSizes = 0;
  this->BlockStartOffsets = 0;
  this->Compressor = 0;

  this->AsciiDataBuffer = 0;
  this->AsciiDataBufferLength = 0;
  this->AsciiDataPosition = 0;

  this->Abort = 0;
  this->Progress = 0;

  // Default byte order to that of this machine.
#ifdef VTK_WORDS_BIGENDIAN
  this->ByteOrder = vtkXMLDataParser::BigEndian;
#else
  this->ByteOrder = vtkXMLDataParser::LittleEndian;
#endif
  this->HeaderType = 32;

  this->AttributesEncoding = VTK_ENCODING_NONE;

  // Have specialized methods for reading array data both inline or
  // appended, however typical tags may use the more general CharacterData
  // methods.
  this->IgnoreCharacterData = 0;
}

//----------------------------------------------------------------------------
vtkXMLDataParser::~vtkXMLDataParser()
{
  this->FreeAllElements();
  delete [] this->OpenElements;
  this->InlineDataStream->Delete();
  this->AppendedDataStream->Delete();
  delete [] this->BlockCompressedSizes;
  delete [] this->BlockStartOffsets;
  this->SetCompressor(0);
  if(this->AsciiDataBuffer) { this->FreeAsciiBuffer(); }
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "AppendedDataPosition: "
     << this->AppendedDataPosition << "\n";
  if(this->RootElement)
  {
    this->RootElement->PrintXML(os, indent);
  }
  if(this->Compressor)
  {
    os << indent << "Compressor: " << this->Compressor << "\n";
  }
  else
  {
    os << indent << "Compressor: (none)\n";
  }
  os << indent << "Progress: " << this->Progress << "\n";
  os << indent << "Abort: " << this->Abort << "\n";
  os << indent << "AttributesEncoding: " << this->AttributesEncoding << "\n";
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::Parse()
{
  // Delete any elements left from previous parsing.
  this->FreeAllElements();

  // Parse the input from the stream.
  int result = this->Superclass::Parse();

  // Check that the input is okay.
  if(result && !this->CheckPrimaryAttributes())
  {
    result = 0;
  }

  return result;
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::Parse(const char*)
{
  vtkErrorMacro("Parsing from a string is not supported.");
  return 0;
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::Parse(const char*, unsigned int)
{
  vtkErrorMacro("Parsing from a string is not supported.");
  return 0;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::StartElement(const char* name, const char** atts)
{
  vtkXMLDataElement* element = vtkXMLDataElement::New();
  element->SetName(name);
  element->SetXMLByteIndex(this->GetXMLByteIndex());
  vtkXMLUtilities::ReadElementFromAttributeArray(element, atts, this->AttributesEncoding);

  const char* id = element->GetAttribute("id");
  if(id)
  {
    element->SetId(id);
  }
  this->PushOpenElement(element);

  if(strcmp(name, "AppendedData") == 0)
  {
    // This is the AppendedData element.
    this->FindAppendedDataPosition();

    // Switch to raw decoder if necessary.
    const char* encoding = element->GetAttribute("encoding");
    if(encoding && (strcmp(encoding, "raw") == 0))
    {
      this->AppendedDataStream->Delete();
      this->AppendedDataStream = vtkInputStream::New();
    }
  }
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::SeekInlineDataPosition(vtkXMLDataElement *element)
{
  istream* stream = this->GetStream();
  if(!element->GetInlineDataPosition())
  {
    // Scan for the start of the actual inline data.
    char c=0;
    stream->clear(stream->rdstate() & ~ios::eofbit);
    stream->clear(stream->rdstate() & ~ios::failbit);
    this->SeekG(element->GetXMLByteIndex());
    while(stream->get(c) && (c != '>'))
    {
      ;
    }
    while(stream->get(c) && element->IsSpace(c))
    {
      ;
    }
    vtkTypeInt64 pos = this->TellG();
    element->SetInlineDataPosition(pos-1);
  }

  // Seek to the data position.
  this->SeekG(element->GetInlineDataPosition());
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::EndElement(const char*)
{
  vtkXMLDataElement* finished = this->PopOpenElement();
  unsigned int numOpen = this->NumberOfOpenElements;
  if(numOpen > 0)
  {
    this->OpenElements[numOpen-1]->AddNestedElement(finished);
    finished->Delete();
  }
  else
  {
    this->RootElement = finished;
  }
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::ParsingComplete()
{
  // If we have reached the appended data section, we stop parsing.
  // This prevents the XML parser from having to walk over the entire
  // appended data section.
  if(this->AppendedDataPosition) { return 1; }
  return this->Superclass::ParsingComplete();
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::CheckPrimaryAttributes()
{
  const char* byte_order = this->RootElement->GetAttribute("byte_order");
  if(byte_order)
  {
    if(strcmp(byte_order, "BigEndian") == 0)
    {
      this->ByteOrder = vtkXMLDataParser::BigEndian;
    }
    else if(strcmp(byte_order, "LittleEndian") == 0)
    {
      this->ByteOrder = vtkXMLDataParser::LittleEndian;
    }
    else
    {
      vtkErrorMacro("Unsupported byte_order=\"" << byte_order << "\"");
      return 0;
    }
  }
  if(const char* header_type = this->RootElement->GetAttribute("header_type"))
  {
    if(strcmp(header_type, "UInt32") == 0)
    {
      this->HeaderType = 32;
    }
    else if(strcmp(header_type, "UInt64") == 0)
    {
      this->HeaderType = 64;
    }
    else
    {
      vtkErrorMacro("Unsupported header_type=\"" << header_type << "\"");
      return 0;
    }
  }
  return 1;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::FindAppendedDataPosition()
{
  // Clear stream fail and eof bits.  We may have already read past
  // the end of the stream when processing the AppendedData element.
  this->Stream->clear(this->Stream->rdstate() & ~ios::failbit);
  this->Stream->clear(this->Stream->rdstate() & ~ios::eofbit);

  // Scan for the start of the actual appended data.
  char c=0;
  vtkTypeInt64 returnPosition = this->TellG();
  this->SeekG(this->GetXMLByteIndex());
  while(this->Stream->get(c) && (c != '>'))
  {
    ;
  }
  while(this->Stream->get(c) && this->IsSpace(c))
  {
    ;
  }

  // Store the start of the appended data.  We skip the first
  // character because it is always a "_".
  this->AppendedDataPosition = this->TellG();

  // If first character was not an underscore, assume it is part of
  // the data.
  if(c != '_')
  {
    vtkWarningMacro("First character in AppendedData is ASCII value "
                    << int(c) << ", not '_'.  Scan for first character "
                    << "started from file position "
                    << this->GetXMLByteIndex()
                    << ".  The return position is " << returnPosition << ".");
    --this->AppendedDataPosition;
  }

  // Restore the stream position.
  this->SeekG(returnPosition);
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::PushOpenElement(vtkXMLDataElement* element)
{
  if(this->NumberOfOpenElements == this->OpenElementsSize)
  {
    unsigned int newSize = this->OpenElementsSize*2;
    vtkXMLDataElement** newOpenElements = new vtkXMLDataElement*[newSize];
    unsigned int i;
    for(i=0; i < this->NumberOfOpenElements;++i)
    {
      newOpenElements[i] = this->OpenElements[i];
    }
    delete [] this->OpenElements;
    this->OpenElements = newOpenElements;
    this->OpenElementsSize = newSize;
  }

  unsigned int pos = this->NumberOfOpenElements++;
  this->OpenElements[pos] = element;
}

//----------------------------------------------------------------------------
vtkXMLDataElement* vtkXMLDataParser::PopOpenElement()
{
  if(this->NumberOfOpenElements > 0)
  {
    --this->NumberOfOpenElements;
    return this->OpenElements[this->NumberOfOpenElements];
  }
  return 0;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::FreeAllElements()
{
  while(this->NumberOfOpenElements > 0)
  {
    --this->NumberOfOpenElements;
    this->OpenElements[this->NumberOfOpenElements]->Delete();
    this->OpenElements[this->NumberOfOpenElements] = 0;
  }
  if(this->RootElement)
  {
    this->RootElement->Delete();
    this->RootElement = 0;
  }
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::ParseBuffer(const char* buffer, unsigned int count)
{
  // Parsing must stop when "<AppendedData" is reached.  Use a search
  // similar to the KMP string search algorithm.
  const char pattern[] = "<AppendedData";
  const int length = sizeof(pattern)-1;

  const char* s = buffer;
  const char* end = buffer + count;
  int matched = this->AppendedDataMatched;
  while(s != end)
  {
    char c = *s++;
    if(c == pattern[matched]) { if(++matched == length) { break; } }
    else { matched = (c == pattern[0])? 1:0; }
  }
  this->AppendedDataMatched = matched;

  // Parse as much of the buffer as is safe.
  if(!this->Superclass::ParseBuffer(buffer, s - buffer)) { return 0; }

  // If we have reached the appended data, artificially finish the
  // document.
  if(matched == length)
  {
    // Parse the rest of the element's opening tag.
    const char* t = s;
    char prev = 0;
    while((t != end) && (*t != '>')) { ++t; }
    if(!this->Superclass::ParseBuffer(s, t-s)) { return 0; }
    if(t > s) { prev = *(t-1); }

    if(t == end)
    {
      // Scan for the real end of the element's opening tag.
      char c=0;
      while(this->Stream->get(c) && (c != '>'))
      {
        prev = c;
        if(!this->Superclass::ParseBuffer(&c, 1)) { return 0; }
      }
    }

    // Artificially end the AppendedData element.
    if(prev != '/')
    {
      if(!this->Superclass::ParseBuffer("/", 1)) { return 0; }
    }
    if(!this->Superclass::ParseBuffer(">", 1)) { return 0; }

    // Artificially end the VTKFile element.
    const char finish[] = "\n</VTKFile>\n";
    if(!this->Superclass::ParseBuffer(finish, sizeof(finish)-1)) { return 0; }
  }

  return 1;
}

//----------------------------------------------------------------------------
template <class T>
size_t vtkXMLDataParserGetWordTypeSize(T*)
{
  return sizeof(T);
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::GetWordTypeSize(int wordType)
{
  size_t size = 1;
  switch (wordType)
  {
    vtkTemplateMacro(
      size = vtkXMLDataParserGetWordTypeSize(static_cast<VTK_TT*>(0))
      );
    default:
      { vtkWarningMacro("Unsupported data type: " << wordType); } break;
  }
  return size;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::PerformByteSwap(void* data, size_t numWords,
                                       size_t wordSize)
{
  char* ptr = static_cast<char*>(data);
  if(this->ByteOrder == vtkXMLDataParser::BigEndian)
  {
    switch (wordSize)
    {
      case 1: break;
      case 2: vtkByteSwap::Swap2BERange(ptr, numWords); break;
      case 4: vtkByteSwap::Swap4BERange(ptr, numWords); break;
      case 8: vtkByteSwap::Swap8BERange(ptr, numWords); break;
      default:
        vtkErrorMacro("Unsupported data type size " << wordSize);
    }
  }
  else
  {
    switch (wordSize)
    {
      case 1: break;
      case 2: vtkByteSwap::Swap2LERange(ptr, numWords); break;
      case 4: vtkByteSwap::Swap4LERange(ptr, numWords); break;
      case 8: vtkByteSwap::Swap8LERange(ptr, numWords); break;
      default:
        vtkErrorMacro("Unsupported data type size " << wordSize);
    }
  }
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::ReadCompressionHeader()
{
#if defined(VTK_HAS_STD_UNIQUE_PTR)
  std::unique_ptr<vtkXMLDataHeader>
    ch(vtkXMLDataHeader::New(this->HeaderType, 3));
#else
  std::auto_ptr<vtkXMLDataHeader>
    ch(vtkXMLDataHeader::New(this->HeaderType, 3));
#endif

  this->DataStream->StartReading();

  // Read the standard part of the header.
  size_t const headerSize = ch->DataSize();
  size_t r = this->DataStream->Read(ch->Data(), headerSize);
  if(r < headerSize)
  {
    vtkErrorMacro("Error reading beginning of compression header.  Read "
                  << r << " of " << headerSize << " bytes.");
    return 0;
  }

  // Byte swap the header to make sure the values are correct.
  this->PerformByteSwap(ch->Data(), ch->WordCount(), ch->WordSize());

  // Get the standard values.
  this->NumberOfBlocks = size_t(ch->Get(0));
  this->BlockUncompressedSize = size_t(ch->Get(1));
  this->PartialLastBlockUncompressedSize = size_t(ch->Get(2));

  // Allocate the size and offset parts of the header.
  ch->Resize(this->NumberOfBlocks);
  delete [] this->BlockCompressedSizes;
  this->BlockCompressedSizes = 0;
  delete [] this->BlockStartOffsets;
  this->BlockStartOffsets = 0;
  if(this->NumberOfBlocks > 0)
  {
    this->BlockCompressedSizes = new size_t[this->NumberOfBlocks];
    this->BlockStartOffsets = new vtkTypeInt64[this->NumberOfBlocks];

    // Read the compressed block sizes.
    size_t len = ch->DataSize();
    if(this->DataStream->Read(ch->Data(), len) < len)
    {
      vtkErrorMacro("Error reading compression header.");
      return 0;
    }

    // Byte swap the sizes to make sure the values are correct.
    this->PerformByteSwap(ch->Data(), ch->WordCount(), ch->WordSize());
  }

  this->DataStream->EndReading();

  // Use the compressed block sizes to calculate the starting offset
  // of each block.
  vtkTypeInt64 offset = 0;
  for(size_t i=0;i < this->NumberOfBlocks;++i)
  {
    size_t const sz = size_t(ch->Get(i));
    this->BlockCompressedSizes[i] = sz;
    this->BlockStartOffsets[i] = offset;
    offset += sz;
  }
  return 1;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::FindBlockSize(vtkTypeUInt64 block)
{
  if(block < this->NumberOfBlocks-(this->PartialLastBlockUncompressedSize?1:0))
  {
    return this->BlockUncompressedSize;
  }
  else
  {
    return this->PartialLastBlockUncompressedSize;
  }
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::ReadBlock(vtkTypeUInt64 block, unsigned char* buffer)
{
  size_t uncompressedSize = this->FindBlockSize(block);
  size_t compressedSize = this->BlockCompressedSizes[block];

  if(!this->DataStream->Seek(this->BlockStartOffsets[block]))
  {
    return 0;
  }

  unsigned char* readBuffer = new unsigned char[compressedSize];

  if(this->DataStream->Read(readBuffer, compressedSize) < compressedSize)
  {
    delete [] readBuffer;
    return 0;
  }

  size_t result =
    this->Compressor->Uncompress(readBuffer, compressedSize,
                                 buffer, uncompressedSize);

  delete [] readBuffer;
  return result > 0;
}

//----------------------------------------------------------------------------
unsigned char* vtkXMLDataParser::ReadBlock(vtkTypeUInt64 block)
{
  unsigned char* decompressBuffer =
    new unsigned char[this->FindBlockSize(block)];
  if(!this->ReadBlock(block, decompressBuffer))
  {
    delete [] decompressBuffer;
    return 0;
  }
  return decompressBuffer;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadUncompressedData(unsigned char* data,
                                              vtkTypeUInt64 startWord,
                                              size_t numWords,
                                              size_t wordSize)
{
  // First read the length of the data.
#if defined(VTK_HAS_STD_UNIQUE_PTR)
  std::unique_ptr<vtkXMLDataHeader>
    uh(vtkXMLDataHeader::New(this->HeaderType, 1));
#else
  std::auto_ptr<vtkXMLDataHeader>
    uh(vtkXMLDataHeader::New(this->HeaderType, 1));
#endif
  size_t const headerSize = uh->DataSize();
  size_t r = this->DataStream->Read(uh->Data(), headerSize);
  if(r < headerSize)
  {
    vtkErrorMacro("Error reading uncompressed binary data header.  "
                  "Read " << r << " of " << headerSize << " bytes.");
    return 0;
  }
  this->PerformByteSwap(uh->Data(), uh->WordCount(), uh->WordSize());
  vtkTypeUInt64 rsize = uh->Get(0);

  // Adjust the size to be a multiple of the wordSize by taking
  // advantage of integer division.  This will only change the value
  // when the input file is invalid.
  vtkTypeUInt64 size = (rsize/wordSize)*wordSize;

  // Convert the start/length into bytes.
  vtkTypeUInt64 offset = startWord*wordSize;
  size_t length = numWords*wordSize;

  // Make sure the begin/end offsets fall within total size.
  if(offset > size)
  {
    return 0;
  }
  vtkTypeUInt64 end = offset+length;
  if(end > size)
  {
    end = size;
  }
  length = end-offset;

  // Read the data.
  if(!this->DataStream->Seek(headerSize+offset))
  {
    return 0;
  }

  // Read data in 2MB blocks and report progress.
  size_t const blockSize = 2097152;
  size_t left = length;
  unsigned char* p = data;
  this->UpdateProgress(0);
  while(left > 0 && !this->Abort)
  {
    // Read this block.
    size_t n = (blockSize < left)? blockSize:left;
    if(!this->DataStream->Read(p, n))
    {
      return 0;
    }

    // Byte swap this block.  Note that n will always be an integer
    // multiple of the word size.
    this->PerformByteSwap(p, n / wordSize, wordSize);

    // Update pointer and counter.
    p += n;
    left -= n;

    // Report progress.
    this->UpdateProgress(float(p-data)/length);
  }
  this->UpdateProgress(1);
  return length/wordSize;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadCompressedData(unsigned char* data,
                                            vtkTypeUInt64 startWord,
                                            size_t numWords,
                                            size_t wordSize)
{
  // Make sure there are data.
  if(numWords == 0)
  {
    return 0;
  }

  // Find the begin and end offsets into the data.
  vtkTypeUInt64 beginOffset = startWord*wordSize;
  vtkTypeUInt64 endOffset = beginOffset+numWords*wordSize;

  // Find the total size of the data.
  vtkTypeUInt64 totalSize = this->NumberOfBlocks*this->BlockUncompressedSize;
  if(this->PartialLastBlockUncompressedSize)
  {
    totalSize -= this->BlockUncompressedSize;
    totalSize += this->PartialLastBlockUncompressedSize;
  }

  // Make sure there's even data to be read
  if(totalSize == 0)
  {
    return 0;
  }

  // Adjust the size to be a multiple of the wordSize by taking
  // advantage of integer division.  This will only change the value
  // when the input file is invalid.
  totalSize = (totalSize/wordSize)*wordSize;

  // Make sure the begin/end offsets fall within the total size.
  if(beginOffset > totalSize)
  {
    return 0;
  }
  if(endOffset > totalSize)
  {
    endOffset = totalSize;
  }

  // Find the range of compression blocks to read.
  vtkTypeUInt64 firstBlock = beginOffset / this->BlockUncompressedSize;
  vtkTypeUInt64 lastBlock = endOffset / this->BlockUncompressedSize;

  // Find the offset into the first block where the data begin.
  size_t beginBlockOffset =
    beginOffset - firstBlock*this->BlockUncompressedSize;

  // Find the offset into the last block where the data end.
  size_t endBlockOffset =
    endOffset - lastBlock*this->BlockUncompressedSize;

  this->UpdateProgress(0);
  if(firstBlock == lastBlock)
  {
    // Everything fits in one block.
    unsigned char* blockBuffer = this->ReadBlock(firstBlock);
    if(!blockBuffer) { return 0; }
    size_t n = endBlockOffset - beginBlockOffset;
    memcpy(data, blockBuffer+beginBlockOffset, n);
    delete [] blockBuffer;

    // Byte swap this block.  Note that n will always be an integer
    // multiple of the word size.
    this->PerformByteSwap(data, n / wordSize, wordSize);
  }
  else
  {
    // Read all the complete blocks first.
    size_t length = endOffset - beginOffset;
    unsigned char* outputPointer = data;
    size_t blockSize = this->FindBlockSize(firstBlock);

    // Read the first block.
    unsigned char* blockBuffer = this->ReadBlock(firstBlock);
    if(!blockBuffer)
    {
      return 0;
    }
    size_t n = blockSize-beginBlockOffset;
    memcpy(outputPointer, blockBuffer+beginBlockOffset, n);
    delete [] blockBuffer;

    // Byte swap the first block.  Note that n will always be an
    // integer multiple of the word size.
    this->PerformByteSwap(outputPointer, n / wordSize, wordSize);

    // Advance the pointer to the beginning of the second block.
    outputPointer += blockSize-beginBlockOffset;

    // Report progress.
    this->UpdateProgress(float(outputPointer-data)/length);

    unsigned int currentBlock = firstBlock+1;
    for(;currentBlock != lastBlock && !this->Abort; ++currentBlock)
    {
      // Read this block.
      if(!this->ReadBlock(currentBlock, outputPointer)) { return 0; }

      // Byte swap this block.  Note that blockSize will always be an
      // integer multiple of the word size.
      this->PerformByteSwap(outputPointer, blockSize / wordSize, wordSize);

      // Advance the pointer to the beginning of the next block.
      outputPointer += this->FindBlockSize(currentBlock);

      // Report progress.
      this->UpdateProgress(float(outputPointer-data)/length);
    }

    // Now read the final block, which is incomplete if it exists.
    if(endBlockOffset > 0 && !this->Abort)
    {
      blockBuffer = this->ReadBlock(lastBlock);
      if(!blockBuffer)
      {
        return 0;
      }
      memcpy(outputPointer, blockBuffer, endBlockOffset);
      delete [] blockBuffer;

      // Byte swap the partial block.  Note that endBlockOffset will
      // always be an integer multiple of the word size.
      this->PerformByteSwap(outputPointer, endBlockOffset / wordSize, wordSize);
    }
  }
  this->UpdateProgress(1);

  // Return the total words actually read.
  return (endOffset - beginOffset)/wordSize;
}

//----------------------------------------------------------------------------
vtkXMLDataElement* vtkXMLDataParser::GetRootElement()
{
  return this->RootElement;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadBinaryData(void* in_buffer,
                                        vtkTypeUInt64 startWord,
                                        size_t numWords,
                                        int wordType)
{
  // Skip real read if aborting.
  if(this->Abort)
  {
    return 0;
  }

  size_t wordSize = this->GetWordTypeSize(wordType);
  void* buffer = in_buffer;

  // Make sure our streams are setup correctly.
  this->DataStream->SetStream(this->Stream);

  // Read the data.
  unsigned char* d = reinterpret_cast<unsigned char*>(buffer);
  size_t actualWords;
  if(this->Compressor)
  {
    if (!this->ReadCompressionHeader())
    {
      vtkErrorMacro("ReadCompressionHeader failed. Aborting read.");
      return 0;
    }
    this->DataStream->StartReading();
    actualWords = this->ReadCompressedData(d, startWord, numWords, wordSize);
    this->DataStream->EndReading();
  }
  else
  {
    this->DataStream->StartReading();
    actualWords = this->ReadUncompressedData(d, startWord, numWords, wordSize);
    this->DataStream->EndReading();
  }

  // Return the actual amount read.
  return this->Abort? 0:actualWords;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadAsciiData(void* buffer,
                                       vtkTypeUInt64 startWord,
                                       size_t numWords,
                                       int wordType)
{
  // Skip real read if aborting.
  if(this->Abort)
  {
    return 0;
  }

  // We assume that ascii data are not very large and parse the entire
  // block into memory.
  this->UpdateProgress(0);

  // Parse the ascii data from the file.
  if(!this->ParseAsciiData(wordType)) { return 0; }

  // Make sure we don't read outside the range of data available.
  vtkTypeUInt64 endWord = startWord + numWords;
  if(this->AsciiDataBufferLength < startWord) { return 0; }
  if(endWord > this->AsciiDataBufferLength)
  {
    endWord = this->AsciiDataBufferLength;
  }
  size_t wordSize = this->GetWordTypeSize(wordType);
  size_t actualWords = endWord - startWord;
  size_t actualBytes = wordSize*actualWords;
  size_t startByte = wordSize*startWord;

  this->UpdateProgress(0.5);

  // Copy the data from the pre-parsed ascii data buffer.
  memcpy(buffer, this->AsciiDataBuffer+startByte, actualBytes);

  this->UpdateProgress(1);

  return this->Abort? 0:actualWords;
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadInlineData(vtkXMLDataElement* element,
                                        int isAscii, void* buffer,
                                        vtkTypeUInt64 startWord,
                                        size_t numWords,
                                        int wordType)
{
  this->DataStream = this->InlineDataStream;
  this->SeekInlineDataPosition(element);
  if(isAscii)
  {
    return this->ReadAsciiData(buffer, startWord, numWords, wordType);
  }
  else
  {
    return this->ReadBinaryData(buffer, startWord, numWords, wordType);
  }
}

//----------------------------------------------------------------------------
size_t vtkXMLDataParser::ReadAppendedData(vtkTypeInt64 offset,
                                          void* buffer,
                                          vtkTypeUInt64 startWord,
                                          size_t numWords,
                                          int wordType)
{
  this->DataStream = this->AppendedDataStream;
  this->SeekG(this->AppendedDataPosition+offset);
  return this->ReadBinaryData(buffer, startWord, numWords, wordType);
}

//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Define a parsing function template.  The extra "long" argument is used
// to help broken compilers select the non-templates below for char and
// unsigned char by making them a better conversion than the template.
template <class T>
T* vtkXMLParseAsciiData(istream& is, int* length, T*, long)
{
  int dataLength = 0;
  int dataBufferSize = 64;

  T* dataBuffer = new T[dataBufferSize];
  T element;

  while(is >> element)
  {
    if(dataLength == dataBufferSize)
    {
      int newSize = dataBufferSize*2;
      T* newBuffer = new T[newSize];
      memcpy(newBuffer, dataBuffer, dataLength*sizeof(T));
      delete [] dataBuffer;
      dataBuffer = newBuffer;
      dataBufferSize = newSize;
    }
    dataBuffer[dataLength++] = element;
  }

  if(length)
  {
    *length = dataLength;
  }

  return dataBuffer;
}

//----------------------------------------------------------------------------
static char* vtkXMLParseAsciiData(istream& is, int* length, char*, int)
{
  int dataLength = 0;
  int dataBufferSize = 64;

  char* dataBuffer = new char[dataBufferSize];
  char element;
  short inElement;

  while(is >> inElement)
  {
    element = inElement;
    if(dataLength == dataBufferSize)
    {
      int newSize = dataBufferSize*2;
      char* newBuffer = new char[newSize];
      memcpy(newBuffer, dataBuffer, dataLength*sizeof(char));
      delete [] dataBuffer;
      dataBuffer = newBuffer;
      dataBufferSize = newSize;
    }
    dataBuffer[dataLength++] = element;
  }

  if(length)
  {
    *length = dataLength;
  }

  return dataBuffer;
}

//----------------------------------------------------------------------------
static unsigned char* vtkXMLParseAsciiData(istream& is,
                                           int* length,
                                           unsigned char*,
                                           int)
{
  int dataLength = 0;
  int dataBufferSize = 64;

  unsigned char* dataBuffer = new unsigned char[dataBufferSize];
  unsigned char element;
  short inElement;

  while(is >> inElement)
  {
    element = inElement;
    if(dataLength == dataBufferSize)
    {
      int newSize = dataBufferSize*2;
      unsigned char* newBuffer = new unsigned char[newSize];
      memcpy(newBuffer, dataBuffer, dataLength*sizeof(unsigned char));
      delete [] dataBuffer;
      dataBuffer = newBuffer;
      dataBufferSize = newSize;
    }
    dataBuffer[dataLength++] = element;
  }

  if(length)
  {
    *length = dataLength;
  }

  return dataBuffer;
}

//----------------------------------------------------------------------------
static signed char* vtkXMLParseAsciiData(istream& is,
                                         int* length,
                                         signed char*,
                                         int)
{
  int dataLength = 0;
  int dataBufferSize = 64;

  signed char* dataBuffer = new signed char[dataBufferSize];
  signed char element;
  short inElement;

  while(is >> inElement)
  {
    element = inElement;
    if(dataLength == dataBufferSize)
    {
      int newSize = dataBufferSize*2;
      signed char* newBuffer = new signed char[newSize];
      memcpy(newBuffer, dataBuffer, dataLength*sizeof(signed char));
      delete [] dataBuffer;
      dataBuffer = newBuffer;
      dataBufferSize = newSize;
    }
    dataBuffer[dataLength++] = element;
  }

  if(length)
  {
    *length = dataLength;
  }

  return dataBuffer;
}

//----------------------------------------------------------------------------
int vtkXMLDataParser::ParseAsciiData(int wordType)
{
  istream& is = *(this->Stream);

  // Don't re-parse the same ascii data.
  if(this->AsciiDataPosition == this->TellG())
  {
    return (this->AsciiDataBuffer? 1:0);
  }

  // Prepare for new data.
  this->AsciiDataPosition = this->TellG();
  if(this->AsciiDataBuffer) { this->FreeAsciiBuffer(); }

  int length = 0;
  void* buffer = 0;
  switch (wordType)
  {
    vtkTemplateMacro(
      buffer = vtkXMLParseAsciiData(is, &length, static_cast<VTK_TT*>(0), 1)
      );
  }

  // Read terminated from failure.  Clear the fail bit so another read
  // can take place later.
  is.clear(is.rdstate() & ~ios::failbit);

  // Save the buffer.
  this->AsciiDataBuffer = reinterpret_cast<unsigned char*>(buffer);
  this->AsciiDataBufferLength = length;
  this->AsciiDataWordType = wordType;
  return (this->AsciiDataBuffer? 1:0);
}

//----------------------------------------------------------------------------
template <class T>
void vtkXMLDataParserFreeAsciiBuffer(T* buffer)
{
  delete [] buffer;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::FreeAsciiBuffer()
{
  void* buffer = this->AsciiDataBuffer;
  switch (this->AsciiDataWordType)
  {
    vtkTemplateMacro(
      vtkXMLDataParserFreeAsciiBuffer(static_cast<VTK_TT*>(buffer))
      );
  }
  this->AsciiDataBuffer = 0;
}

//----------------------------------------------------------------------------
void vtkXMLDataParser::UpdateProgress(float progress)
{
  this->Progress = progress;
  double dProgress=progress;
  this->InvokeEvent(vtkCommand::ProgressEvent, &dProgress);
}