-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathStreamIndexedIO.cpp
2931 lines (2378 loc) · 74.4 KB
/
StreamIndexedIO.cpp
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
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2014, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <algorithm>
#include <list>
#include <iostream>
#include <cassert>
#include <map>
#include <set>
#include "boost/tokenizer.hpp"
#include "boost/optional.hpp"
#include "boost/format.hpp"
#include "boost/iostreams/device/file.hpp"
#include "boost/iostreams/filtering_streambuf.hpp"
#include "boost/iostreams/filtering_stream.hpp"
#include "boost/iostreams/stream.hpp"
#include "boost/iostreams/filter/gzip.hpp"
#include "tbb/spin_rw_mutex.h"
#include "IECore/ByteOrder.h"
#include "IECore/MemoryStream.h"
#include "IECore/MessageHandler.h"
#include "IECore/StreamIndexedIO.h"
#include "IECore/VectorTypedData.h"
#include "IECore/MurmurHash.h"
#define HARDLINK 127
#define SUBINDEX_DIR 126
static const Imf::Int64 g_unversionedMagicNumber = 0x0B00B1E5;
static const Imf::Int64 g_versionedMagicNumber = 0xB00B1E50;
/// File format history:
/// Version 4: introduced hard links (automatic data deduplication), also ability to store InternedString data.
/// Version 5: introduced subindex as zipped data blocks (to reduce size of the main index).
/// Hard links are represented as regular data nodes, that points to same data on file (no removal of data ever).
/// Removed the linkCount field on the data nodes.
/// \todo Store SubIndexSize and NodeCount as unsigned 64bit integers
static const Imf::Int64 g_currentVersion = 5;
/// FileFormat ::= Data Index IndexOffset Version MagicNumber
/// Data ::= DataEntry*
/// Index ::= zip(StringCache NodeTree FreePages)
/// DataEntry ::= Stores data from nodes:
/// [Data nodes] binary data indexed by DataOffset/DataSize and
/// [Subindex] SubIndexSize zip(NodeCount NodeTree*) indexed by SubIndexOffset.
/// SubIndexSize :: = uint32 - number of bytes in the zipped subindex that follows
/// StringCache ::= NumStrings String*
/// NumStrings ::= int64
/// String ::= StringLength char*
/// StringLength ::= int64
/// NodeTree Node* ( A Directory node followed by it's child nodes )
/// Node ::= EntryType EntryStringCacheID NodeCount ( if EntryType == Directory )
/// EntryType EntryStringCacheID DataType ArrayLength DataOffset DataSize ( if EntryType == File )
/// EntryType EntryStringCacheID SubIndexOffset ( If EntryType == SUBINDEX_DIR )
/// EntryType ::= char ( value from IndexedIO::EntryType )
/// EntryStringCacheID ::= int64 ( index in StringCache )
/// DataType ::= char ( value from IndexedIO::DataType )
/// ArrayLength ::= int64 ( if DataType is array, then this tells how long they are )
/// NodeID ::= int64 ( unique Id of this node in the file )
/// ParentNodeID ::= int64 ( Id for the parent node )
/// DataOffset ::= int64 ( this is offset where the data is located )
/// DataSize ::= int64 ( number of bytes stored in the data section )
/// NodeCount ::= uint32 ( number of child nodes in the directory - stored right after this node leading to recursive definition of a tree )
/// SubIndexOffset :: = int64 ( offset in the Data block where there's a zipped index that contains all the child nodes from this node - and possibly other nodes )
/// FreePages ::= NumFreePages FreePage*
/// NumFreePages ::= int64
/// FreePage ::= FreePageOffset FreePageSize
/// FreePageOffset ::= int64
/// FreePageSize ::= int64
/// IndexOffset ::= int64 ( offset in the file where the Index zipped block starts )
/// Version ::= int64 (file format version)
/// MagicNumber ::= int64
using namespace IECore;
namespace io = boost::iostreams;
IE_CORE_DEFINERUNTIMETYPEDDESCRIPTION( StreamIndexedIO )
//// Templated functions for stream files //////
template<typename F, typename T>
void writeLittleEndian( F &f, const T &n )
{
const T nl = asLittleEndian<>(n);
f.write( (const char*) &nl, sizeof(T) );
}
template<typename F, typename T>
void readLittleEndian( F &f, T &n )
{
f.read( (char*) &n, sizeof(T) );
if (bigEndian())
{
n = reverseBytes<>(n);
}
else
{
/// Already little endian
}
}
class StreamIndexedIO::StringCache
{
public:
StringCache() : m_prevId(0), m_ioBuffer(0), m_ioBufferLen(0)
{
m_idToStringMap.reserve(100);
}
template < typename F >
StringCache( F &f ) : m_prevId(0), m_ioBuffer(0), m_ioBufferLen(0)
{
Imf::Int64 sz;
readLittleEndian(f,sz);
m_idToStringMap.reserve(sz + 100);
for (Imf::Int64 i = 0; i < sz; ++i)
{
const char *s = read(f);
Imf::Int64 id;
readLittleEndian( f,id );
m_prevId = std::max( id, m_prevId );
m_stringToIdMap[s] = id;
if ( id >= m_idToStringMap.size() )
{
m_idToStringMap.resize(id+1, (const char *)"");
}
m_idToStringMap[id] = s;
}
}
template < typename F >
void write( F &f ) const
{
Imf::Int64 sz = m_stringToIdMap.size();
writeLittleEndian( f,sz );
for (StringToIdMap::const_iterator it = m_stringToIdMap.begin();
it != m_stringToIdMap.end(); ++it)
{
write(f, it->first);
writeLittleEndian(f,it->second);
}
}
Imf::Int64 find( const IndexedIO::EntryID &s ) const
{
StringToIdMap::const_iterator it = m_stringToIdMap.find( s );
if ( it == m_stringToIdMap.end() )
{
throw IOException( (boost::format ( "StringCache: could not find string %s!" ) % s.value() ).str() );
}
return it->second;
}
Imf::Int64 find( const IndexedIO::EntryID &s, bool errIfNotFound = true )
{
StringToIdMap::const_iterator it = m_stringToIdMap.find( s );
if ( it == m_stringToIdMap.end() )
{
if (errIfNotFound)
{
throw IOException( (boost::format ( "StringCache: could not find string %s!" ) % s.value() ).str() );
}
Imf::Int64 id = ++m_prevId;
m_stringToIdMap[s] = id;
if ( id >= m_idToStringMap.size() )
{
m_idToStringMap.resize(id+1, (const char *)"");
}
m_idToStringMap[id] = s;
return id;
}
else
{
return it->second;
}
}
const IndexedIO::EntryID &findById( const Imf::Int64 &id ) const
{
if ( id >= m_idToStringMap.size() )
{
throw IOException( (boost::format ( "StringCache: invalid string ID %d!" ) % id ).str() );
}
return m_idToStringMap[id];
}
void add( const IndexedIO::EntryID &s )
{
(void)find(s, false);
}
Imf::Int64 size() const
{
return m_stringToIdMap.size();
}
protected:
template < typename F >
void write( F &f, const std::string &s ) const
{
Imf::Int64 sz = s.size();
writeLittleEndian( f, sz );
/// Does not include null terminator
f.write( s.c_str(), sz * sizeof(char) );
}
template < typename F >
const char *read( F &f ) const
{
Imf::Int64 sz;
readLittleEndian( f, sz );
if ( m_ioBufferLen < sz + 1 )
{
if ( m_ioBuffer )
{
delete [] m_ioBuffer;
}
m_ioBufferLen = sz+1;
m_ioBuffer = new char[m_ioBufferLen];
}
f.read( m_ioBuffer, sz*sizeof(char));
m_ioBuffer[sz] = '\0';
return m_ioBuffer;
}
Imf::Int64 m_prevId;
typedef std::map< IndexedIO::EntryID, Imf::Int64 > StringToIdMap;
typedef std::vector< IndexedIO::EntryID > IdToStringMap;
StringToIdMap m_stringToIdMap;
IdToStringMap m_idToStringMap;
mutable char *m_ioBuffer;
mutable unsigned long m_ioBufferLen;
};
/// NodeBase is a base class for nodes representing the index
// It's designed to keep the size of nodes to a minimum for dealing with large indexes
// As a result we deliberately not deriving from RefCounted to save the size of the refcount and the vptr (due to the virtual methods)
// Because it has no virtual destructor, we provide the destroy() function that carefully casts the Node pointer to the appropriate derived type before deleting it.
// NodeType enumerates the derived types, and m_nodeType is defined at construction by the derived classes
class NodeBase
{
public :
typedef enum {
Base,
SmallData,
Data,
Directory,
SubIndex
} NodeType;
NodeBase( NodeType type, IndexedIO::EntryID name ) : m_name(name), m_nodeType(type) {}
inline const IndexedIO::EntryID &name()
{
return m_name;
}
inline NodeType nodeType()
{
return static_cast<NodeType>(m_nodeType);
}
static bool compareNames(const NodeBase* a, const NodeBase* b)
{
return a->m_name < b->m_name;
}
static void destroy( NodeBase *n );
protected :
// name of the node in the current directory
const IndexedIO::EntryID m_name;
// using char instead of enum to compact members in one word
const char m_nodeType;
};
/// Class that represents small data nodes
class SmallDataNode : public NodeBase
{
public :
typedef uint16_t Length;
typedef uint32_t Size;
static const size_t maxArrayLength = UINT16_MAX;
static const size_t maxSize = UINT32_MAX;
SmallDataNode( IndexedIO::EntryID name, IndexedIO::DataType dataType, Imf::Int64 arrayLength, Imf::Int64 size, Imf::Int64 offset ) :
NodeBase(NodeBase::SmallData, name), m_dataType(dataType), m_arrayLength((Length)arrayLength), m_size((Size)size), m_offset(offset) {}
inline IndexedIO::DataType dataType()
{
return static_cast<IndexedIO::DataType>(m_dataType);
}
inline Imf::Int64 arrayLength()
{
return m_arrayLength;
}
inline Imf::Int64 size()
{
return m_size;
}
inline Imf::Int64 offset()
{
return m_offset;
}
protected :
/// data fields from IndexedIO::Entry
// using char instead of enum to compact members in one word
const char m_dataType;
/// data fields from IndexedIO::Entry
const Length m_arrayLength;
/// The size of this node's data chunk within the file
const Size m_size;
/// The offset in the file to this node's data
const Imf::Int64 m_offset;
};
/// Class that represents Data nodes
class DataNode : public NodeBase
{
public :
static const size_t maxArrayLength = UINT64_MAX;
static const size_t maxSize = UINT64_MAX;
DataNode( IndexedIO::EntryID name, IndexedIO::DataType dataType, Imf::Int64 arrayLength, Imf::Int64 size, Imf::Int64 offset ) :
NodeBase(NodeBase::Data, name), m_dataType(dataType), m_arrayLength(arrayLength), m_size(size), m_offset(offset) {}
inline IndexedIO::DataType dataType()
{
return m_dataType;
}
inline Imf::Int64 arrayLength()
{
return m_arrayLength;
}
inline Imf::Int64 size()
{
return m_size;
}
inline Imf::Int64 offset()
{
return m_offset;
}
void copyFrom( DataNode *other )
{
m_dataType = other->m_dataType;
m_arrayLength = other->m_arrayLength;
m_offset = other->m_offset;
m_size = other->m_size;
}
protected :
/// data fields from IndexedIO::Entry
IndexedIO::DataType m_dataType;
/// data fields from IndexedIO::Entry
Imf::Int64 m_arrayLength;
/// The size of this node's data chunk within the file
Imf::Int64 m_size;
/// The offset in the file to this node's data
Imf::Int64 m_offset;
};
/// A compressed subindex node
class SubIndexNode : public NodeBase
{
public :
SubIndexNode(IndexedIO::EntryID name, Imf::Int64 offset) : NodeBase(NodeBase::SubIndex, name), m_offset(offset) {}
inline Imf::Int64 offset()
{
return m_offset;
}
protected :
/// The offset in the file to this node's subindex block if m_subindex is not NoSubIndex.
const Imf::Int64 m_offset;
};
/// A directory node within an index
/// It also represents subindex directory nodes by setting m_subindex at the root and all it's child nodes to true.
class DirectoryNode : public NodeBase
{
public :
/// Directory nodes can save it's children to sub-indexes to free resources and reduce the size of the main index.
/// Once saved to a subindex, they become read-only.
enum SubIndexMode {
NoSubIndex = 0,
SavedSubIndex,
LoadedSubIndex,
};
typedef std::vector< NodeBase* > ChildMap;
// regular constructor
DirectoryNode(IndexedIO::EntryID name) : NodeBase(NodeBase::Directory, name), m_subindex(NoSubIndex), m_sortedChildren(false), m_subindexChildren(false), m_offset(0), m_parent(0) {}
// constructor used when building a directory based on an existing SubIndexNode (because we want to load the contents soon).
DirectoryNode( SubIndexNode *subindex, DirectoryNode *parent ) : NodeBase(NodeBase::Directory, subindex->name()), m_subindex(SavedSubIndex), m_sortedChildren(false), m_subindexChildren(false), m_offset(subindex->offset()), m_parent(parent) {}
// returns what's the state of this directory, whether it's contents are in a subindex and whether they have been loaded or not.
inline SubIndexMode subindex()
{
return static_cast<SubIndexMode>(m_subindex);
}
inline bool subindexChildren() const
{
return m_subindexChildren;
}
inline Imf::Int64 offset() const
{
return m_offset;
}
inline DirectoryNode *parent()
{
return m_parent;
}
/// Returns the current list of child Nodes.
// This function is not thread-safe and Index::lockDirectory must be used in read-only access
// \todo we may want to restrict more the access to the internal children and add the manipulation methods in the class instead.
inline ChildMap &children()
{
return m_children;
}
// This function is not thread-safe and Index::lockDirectory must be used in read-only access
inline void sortChildren()
{
if ( !m_sortedChildren )
{
std::sort( m_children.begin(), m_children.end(), NodeBase::compareNames );
m_sortedChildren = true;
}
}
// This function is not thread-safe and Index::lockDirectory must be used in read-only access
inline ChildMap::iterator findChild( IndexedIO::EntryID name )
{
sortChildren();
NodeBase search(NodeBase::Base, name);
ChildMap::iterator it = std::lower_bound(m_children.begin(), m_children.end(), &search, NodeBase::compareNames );
if ( it != m_children.end() )
{
if ( (*it)->name() != name )
{
return m_children.end();
}
}
return it;
}
/// registers a child node in this node
void registerChild( NodeBase* c );
void path( IndexedIO::EntryIDList &result ) const;
// Function that changes the SubIndex Mode to SavedSubIndex and saves memory by deallocating it's children.
void setSubIndexOffset( Imf::Int64 offset );
// Indicates to this Directory that it's contents have been retrieved from the subindex.
void recoveredSubIndex();
protected :
char m_subindex; // using char instead of enum to compact members in one word
bool m_sortedChildren; // same as above
bool m_subindexChildren; // true if one or more children are subindex. Helps avoiding the mutex...
/// The offset in the file to this node's subindex block if m_subindex is not NoSubIndex.
Imf::Int64 m_offset;
/// A pointer to the parent node in the tree - will be NULL for the root node
DirectoryNode* m_parent;
/// Sorted list of node's children (DirectoryNode or DataNode/SmallDataNode)
ChildMap m_children;
};
// holds the private member data for StreamIndexedIO instance and provides high level access to the directory nodes, including thread-safety
class StreamIndexedIO::Node
{
public :
/// Construct a new Node in the given index with the given numeric id
Node(StreamIndexedIO::Index* index, DirectoryNode *dirNode);
void childNames( IndexedIO::EntryIDList &names ) const;
void childNames( IndexedIO::EntryIDList &names, IndexedIO::EntryType ) const;
const IndexedIO::EntryID &name() const;
bool hasChild( const IndexedIO::EntryID &name ) const;
// Returns the named child directory node or NULL if not existent. Loads the subindex for the child nodes (if applicable).
DirectoryNode* directoryChild( const IndexedIO::EntryID &name ) const;
/// returns information about the Data node
inline bool dataChildInfo( const IndexedIO::EntryID &name, size_t &offset, size_t &size ) const;
DirectoryNode* addChild( const IndexedIO::EntryID & childName );
void addDataChild( const IndexedIO::EntryID & childName, IndexedIO::DataType dataType, size_t arrayLen, size_t offset, size_t size );
void removeChild( const IndexedIO::EntryID &childName, bool throwException = true );
StreamIndexedIO::IndexPtr m_idx;
DirectoryNode *m_node;
};
/// A tree to represent nodes in a filesystem, along with their locations in a file.
class StreamIndexedIO::Index : public RefCounted
{
public:
friend class Node;
/// Construct an index from reading a file stream.
Index( StreamIndexedIO::StreamFilePtr stream );
virtual ~Index();
/// function called right after construction
void openStream();
DirectoryNode *root() const;
/// Allocate a new chunk of data of the requested size, returning its offset within the file
Imf::Int64 allocate( Imf::Int64 sz );
/// Deallocate a Data node's data block from the file.
template< typename D >
void deallocate( D* n );
/// Queries the string cache
StringCache &stringCache();
StreamIndexedIO::StreamFile &streamFile() const;
/// flushes index to the file
void flush();
/// Returns the offset after saving the data to file or the offset for a previouly saved data (with matching hash)
/// \param prefixSize If true than it will prepend to the block, the size of it
Imf::Int64 writeUniqueData( const char *data, size_t size, bool prefixSize = false );
/// flushes the children of the given directory node to a subindex in the file
void commitNodeToSubIndex( DirectoryNode *n );
/// read the subindex that contains the children of the given node
void readNodeFromSubIndex( DirectoryNode *n );
typedef tbb::spin_rw_mutex Mutex;
typedef Mutex::scoped_lock MutexLock;
/// Returns an appropriate mutex scoped lock to access the given Directory node.
/// It selects on mutex from the pool, reducing the changes of blocking other threads that are accessing different locations.
void lockDirectory( MutexLock &lock, const DirectoryNode *n, bool writeAccess = false ) const;
protected:
static const int MAX_MUTEXES = 11;
/// defines a pool of mutexes for thread-safe access to the Node hierarchy
mutable Mutex m_mutexes[ MAX_MUTEXES ];
DirectoryNode *m_root;
/// we keep all the removed nodes alive until the Index destruction
std::vector< NodeBase * > m_removedNodes;
Imf::Int64 m_version;
bool m_hasChanged;
Imf::Int64 m_offset;
Imf::Int64 m_next;
// only used on Version <= 4
typedef std::vector< NodeBase* > IndexToNodeMap;
IndexToNodeMap m_indexToNodeMap;
typedef std::map< std::pair<MurmurHash,unsigned int>, Imf::Int64 > HashToDataMap;
HashToDataMap m_hashToDataMap;
StringCache m_stringCache;
StreamIndexedIO::StreamFilePtr m_stream;
struct FreePage;
typedef std::map< Imf::Int64, FreePage* > FreePagesOffsetMap;
typedef std::multimap< Imf::Int64, FreePage* > FreePagesSizeMap;
FreePagesOffsetMap m_freePagesOffset;
FreePagesSizeMap m_freePagesSize;
struct FreePage
{
FreePage( Imf::Int64 offset, Imf::Int64 sz ) : m_offset(offset), m_size(sz) {}
Imf::Int64 m_offset;
Imf::Int64 m_size;
FreePagesOffsetMap::iterator m_offsetIterator;
FreePagesSizeMap::iterator m_sizeIterator;
};
void addFreePage( Imf::Int64 offset, Imf::Int64 sz );
void deallocateWalk( NodeBase* n );
/// Write the index to the file stream
Imf::Int64 write();
/// Write the node (and all child nodes) to a stream
template < typename F >
void writeNode( DirectoryNode *n, F &f );
/// Write the subindex node to a stream
template < typename F >
void writeNode( SubIndexNode *n, F &f );
/// Write the data node to a stream
template < typename F, typename D >
void writeDataNode( D *n, F &f );
/// Serialize all the node's children to a stream
template < typename F >
void writeNodeChildren( DirectoryNode *n, F &f );
template < typename F >
void read( F &f );
/// Read method used on previous file format versions up to version 4
/// Returns a newly created Node.
template < typename F >
NodeBase *readNodeV4( F &f );
/// Replace the contents of this node with data read from a stream.
/// Returns a newly created Node.
template < typename F >
NodeBase *readNode( F &f );
};
///////////////////////////////////////////////
//
// NodeBase
//
///////////////////////////////////////////////
void NodeBase::destroy( NodeBase *n )
{
if ( !n )
{
return;
}
switch( n->nodeType() )
{
case NodeBase::Directory :
{
DirectoryNode *dn = static_cast< DirectoryNode *>(n);
for (DirectoryNode::ChildMap::const_iterator it = dn->children().begin(); it != dn->children().end(); ++it)
{
destroy( *it );
}
delete dn;
break;
}
case NodeBase::Data :
{
DataNode *dn = static_cast< DataNode *>(n);
delete dn;
break;
}
case NodeBase::SmallData :
{
SmallDataNode *dn = static_cast< SmallDataNode *>(n);
delete dn;
break;
}
case NodeBase::SubIndex :
{
SubIndexNode *dn = static_cast< SubIndexNode *>(n);
delete dn;
break;
}
default:
throw Exception("Unknown node type!");
}
}
///////////////////////////////////////////////
//
// DirectoryNode
//
///////////////////////////////////////////////
void DirectoryNode::registerChild( NodeBase* c )
{
if ( !c )
{
throw Exception("Invalid pointer for child node!!");
}
if ( m_children.size() >= UINT32_MAX )
{
// we currently save childCount as a uint32... so we prevent new children by construction.
throw IOException("StreamIndexedIO: Too many children under the same node!");
}
if ( c->nodeType() == NodeBase::Directory )
{
DirectoryNode *childNode = static_cast< DirectoryNode *>(c);
if (childNode->m_parent)
{
throw IOException("StreamIndexedIO: Node already has parent!");
}
childNode->m_parent = this;
}
else if ( c->nodeType() == NodeBase::SubIndex )
{
m_subindexChildren = true;
}
m_children.push_back( c );
m_sortedChildren = false;
}
void DirectoryNode::path( IndexedIO::EntryIDList &result ) const
{
if ( m_parent )
{
m_parent->path( result );
result.push_back( m_name );
}
}
void DirectoryNode::setSubIndexOffset( Imf::Int64 offset )
{
m_offset = offset;
// mark this node as a saved in a subindex
m_subindex = DirectoryNode::SavedSubIndex;
// dealloc all the child nodes
for (DirectoryNode::ChildMap::const_iterator it = m_children.begin(); it != m_children.end(); ++it)
{
NodeBase::destroy( *it );
}
// remove all children from this node
m_children.clear();
}
void DirectoryNode::recoveredSubIndex()
{
m_subindex = DirectoryNode::LoadedSubIndex;
}
///////////////////////////////////////////////
//
// StreamIndexedIO::Node (begin)
//
///////////////////////////////////////////////
StreamIndexedIO::Node::Node(Index* index, DirectoryNode *dirNode) : m_idx(index), m_node(dirNode)
{
}
bool StreamIndexedIO::Node::hasChild( const IndexedIO::EntryID &name ) const
{
Index::MutexLock lock;
m_idx->lockDirectory( lock, m_node );
DirectoryNode::ChildMap::const_iterator cit = m_node->findChild( name );
return cit != m_node->children().end();
}
DirectoryNode* StreamIndexedIO::Node::directoryChild( const IndexedIO::EntryID &name ) const
{
Index::MutexLock lock;
m_idx->lockDirectory( lock, m_node );
DirectoryNode::ChildMap::iterator it = m_node->findChild( name );
if ( it != m_node->children().end() )
{
if ( (*it)->nodeType() == NodeBase::Directory )
{
DirectoryNode *dir = static_cast< DirectoryNode *>( (*it) );
if ( dir->subindex() == DirectoryNode::SavedSubIndex )
{
if ( m_node->subindexChildren() )
{
lock.release(); /// we will not change the children dictionary, so we release the lock!
}
// this can occur when the user flushed a directory and right after tries to access it.
m_idx->readNodeFromSubIndex( dir );
}
return dir;
}
else if ( (*it)->nodeType() == NodeBase::SubIndex )
{
SubIndexNode *subIndex = static_cast< SubIndexNode *>( (*it) );
// build a Directory that knows it's flushed to a subindex.
DirectoryNode *newDir = new DirectoryNode( subIndex, m_node );
lock.release(); /// we release the lock while loading data..
m_idx->readNodeFromSubIndex( newDir );
// now that we loaded the whole thing, lock our Index for writing
m_idx->lockDirectory( lock, m_node, true );
// there's a chance that someone else already replaced the pointer...
if ( (*it)->nodeType() == NodeBase::Directory )
{
lock.release(); /// we release the lock because we won't change the children anyways..
NodeBase::destroy( newDir );
return static_cast< DirectoryNode *>(*it);
}
// replace SubIndex by Directory node.
(*it) = newDir;
// and now we are ok to delete the SubIndexNode..
delete subIndex;
return newDir;
}
}
return 0;
}
bool StreamIndexedIO::Node::dataChildInfo( const IndexedIO::EntryID &name, size_t &offset, size_t &size ) const
{
Index::MutexLock lock;
m_idx->lockDirectory( lock, m_node );
DirectoryNode::ChildMap::const_iterator cit = m_node->findChild( name );
if ( cit != m_node->children().end() )
{
NodeBase *p = *cit;
if ( p->nodeType() == NodeBase::Data )
{
DataNode *n = static_cast< DataNode *>( p );
offset = n->offset();
size = n->size();
return true;
}
else if ( p->nodeType() == NodeBase::SmallData )
{
SmallDataNode *n = static_cast< SmallDataNode *>( p );
offset = n->offset();
size = n->size();
return true;
}
}
return false;
}
DirectoryNode* StreamIndexedIO::Node::addChild( const IndexedIO::EntryID &childName )
{
if ( m_node->subindex() )
{
throw Exception( "Cannot modify the file at current location! It was already committed to the file." );
}
if ( hasChild(childName) )
{
return 0;
}
DirectoryNode* child = new DirectoryNode(childName);
if ( !child )
{
throw Exception( "Failed to allocate node!" );
}
m_idx->m_stringCache.add( childName );
m_node->registerChild( child );
m_idx->m_hasChanged = true;
return child;
}
void StreamIndexedIO::Node::addDataChild( const IndexedIO::EntryID &childName, IndexedIO::DataType dataType, size_t arrayLen, size_t offset, size_t size )
{
if ( m_node->subindex() )
{
throw Exception( "Cannot modify the file at current location! It was already committed to the file." );
}
if ( hasChild(childName) )
{
throw IOException( "StreamIndexedIO: Could not insert node '" + childName.value() + "' into index" );
}
m_idx->m_stringCache.add( childName );
if ( arrayLen <= SmallDataNode::maxArrayLength && size <= SmallDataNode::maxSize )
{
SmallDataNode* child = new SmallDataNode(childName, dataType, arrayLen, size, offset);
if ( !child )
{
throw Exception( "Failed to allocate node!" );
}
m_node->registerChild( child );
}
else
{
DataNode* child = new DataNode(childName, dataType, arrayLen, size, offset);
if ( !child )
{
throw Exception( "Failed to allocate node!" );