-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVFS.hpp
1309 lines (1108 loc) · 44.9 KB
/
VFS.hpp
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
/*
* MIT License
*
* Copyright (c) 2020 Christian Tost
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef VFS_HPP
#define VFS_HPP
#include <string>
#include <chrono>
#include <vector>
#include <memory>
#include <stdexcept>
#include <algorithm>
#include <string.h>
#include <mutex>
namespace VFS
{
#define CHUNK_SIZE 4096
class CVFS;
class CVFSNode;
class CVFSFileStream;
using VFSNode = std::shared_ptr<CVFSNode>;
using VFSFileStream = std::shared_ptr<CVFSFileStream>;
enum class VFSError
{
CANT_CREATE_DIR,
CANT_CREATE_FILE,
CANT_OPEN_FILE,
OUT_OF_MEM,
NODE_IS_FILE,
NODE_IS_DIR,
NODE_ALREADY_EXISTS,
NODE_DOESNT_EXISTS,
FAILED_TO_READ_STREAM,
CANT_CREATE_FILESYSTEM
};
enum class FileMode
{
READ = 1,
WRITE = 2,
RW = (READ | WRITE),
APPEND = 4
};
inline FileMode operator | (FileMode lhs, FileMode rhs)
{
return static_cast<FileMode>(static_cast<int>(lhs) | static_cast<int>(rhs));
}
inline FileMode& operator |= (FileMode& lhs, FileMode rhs)
{
lhs = lhs | rhs;
return lhs;
}
inline FileMode operator & (FileMode lhs, FileMode rhs)
{
return static_cast<FileMode>(static_cast<int>(lhs) & static_cast<int>(rhs));
}
inline FileMode& operator &= (FileMode& lhs, FileMode rhs)
{
lhs = lhs & rhs;
return lhs;
}
enum class Cursor
{
BEG,
CUR,
END
};
class CVFSException : public std::exception
{
public:
CVFSException() {}
CVFSException(VFSError Type) : m_ErrType(Type) {}
CVFSException(const std::string &Msg, VFSError Type) : m_Msg(Msg), m_ErrType(Type) {}
const char *what() const noexcept override
{
return m_Msg.c_str();
}
VFSError GetErrType() const noexcept
{
return m_ErrType;
}
private:
std::string m_Msg;
VFSError m_ErrType;
};
/**
* @brief Base of all nodes.
*/
class CVFSNode
{
friend CVFS;
public:
CVFSNode()
{
m_Created = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
m_Accessed = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
}
CVFSNode(const CVFSNode &node)
{
m_Name = node.m_Name;
m_IsDir = node.m_IsDir;
m_Created = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
m_Accessed = node.m_Accessed;
}
/**
* @return Gets the name of the node.
*/
inline std::string Name() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_Name;
}
/**
* @return Returns true if this node is a dir.
*/
inline bool IsDir() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_IsDir;
}
/**
* @return Returns the creation time of the node.
*/
inline time_t Created() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_Created;
}
/**
* @return Returns the last access time of the node.
*/
inline time_t Accessed() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_Accessed;
}
/**
* @return Returns a copy of this node.
*/
virtual VFSNode Copy() = 0;
virtual ~CVFSNode() = default;
protected:
std::string m_Name;
bool m_IsDir;
time_t m_Created;
time_t m_Accessed;
mutable std::mutex m_UpdateLock;
};
class CVFS
{
friend CVFSFileStream;
public:
CVFS(/* args */)
{
//Creates the root node.
m_Root = VFSDir(new CVFSDir("/"));
}
/**
* @brief Create a new directory.
*
* @param Path: Path to the directory.
* @param Force: Creates all parent dirs, if they aren't exists.
*
* @throw Throws a CVFSException, if the dir can't be created or the system is out of memory.
*/
void CreateDir(const std::string &Path, bool Force = false)
{
auto Dirs = SplitPath(Path);
auto CurDir = m_Root;
for (size_t i = 0; i < Dirs.size(); i++)
{
std::string Dir = Dirs[i];
auto node = CurDir->Search(Dir);
//Creates the directory either if Force is true or we are at the end of the path.
if(!node && (Force || (i == Dirs.size() - 1)))
{
VFSDir tmp;
try
{
tmp = VFSDir(new CVFSDir(Dir));
CurDir->AppendChild(tmp);
}
catch(const std::bad_alloc &e)
{
throw CVFSException("Can't create directory. Out of mem. bad_alloc: " + std::string(e.what()), VFSError::OUT_OF_MEM);
}
CurDir = tmp;
}
else if(!node || !node->IsDir())
throw CVFSException("Can't create directory", VFSError::CANT_CREATE_DIR);
else
CurDir = std::static_pointer_cast<CVFSDir>(node);
}
}
/**
* @return Gets the information of a given node. Returns null if the node wasn't found.
*/
VFSNode GetNodeInfo(const std::string &Path)
{
auto Dirs = SplitPath(Path);
auto CurDir = m_Root;
VFSNode Ret;
if(Path == "/")
Ret = m_Root;
for (size_t i = 0; i < Dirs.size(); i++)
{
std::string Dir = Dirs[i];
auto node = CurDir->Search(Dir);
if(node && (node->IsDir() || (i == Dirs.size() - 1))) //"Go into" the directory.
{
Ret = node;
CurDir = std::static_pointer_cast<CVFSDir>(node);
}
else
{
Ret = nullptr;
break;
}
}
return Ret;
}
/**
* @return Checks if a given node already exists. Return true if the node exists.
*/
bool NodeExists(const std::string &Path)
{
return GetNodeInfo(Path) != nullptr;
}
/**
* @return Gets a list of the content of a directory.
*
* @throw Throws a CVFSException, if the given node is a file.
*/
std::vector<VFSNode> List(const std::string &Path)
{
auto node = GetNodeInfo(Path);
return List(node);
}
/**
* @return Gets a list of the content of a directory.
*
* @throw Throws a CVFSException, if the given node is a file.
*/
std::vector<VFSNode> List(VFSNode node)
{
std::vector<VFSNode> Ret;
if(node && node->IsDir())
{
auto Dir = std::static_pointer_cast<CVFSDir>(node);
Ret = Dir->GetChilds();
}
else if(node && !node->IsDir())
throw CVFSException("Given node is not a directory", VFSError::NODE_IS_FILE);
return Ret;
}
/**
* @brief Creates or opens a file.
*
* @param Path: Path to the file.
* @param mode: Access mode.
*
* @throw Throws a CVFSException, if the given node is a directory or if the file can't opened for readonly.
*/
VFSFileStream Open(const std::string &Path, FileMode mode);
/**
* @return Returns the file size.
*/
size_t FileSize(VFSNode node)
{
if(!node->IsDir())
{
auto file = std::static_pointer_cast<CVFSFile>(node);
return file->Size();
}
else if(node && !node->IsDir())
throw CVFSException("Given node is not a file.", VFSError::NODE_IS_DIR);
return 0;
}
/**
* @brief Renames a node.
*
* @param Path: Path to the node.
* @param Name: New Name of the node.
*
* @throw Throws a CVFSException, if a node with the given name already exists or the node doesn't exists.
*/
void Rename(const std::string &Path, const std::string &Name)
{
if(NodeExists(Path))
{
if(!NodeExists(ExtractPath(Path) + "/" + Name))
{
auto Parent = std::static_pointer_cast<CVFSDir>(GetNodeInfo(ExtractPath(Path)));
Parent->RenameChild(ExtractName(Path), Name);
}
else
throw CVFSException("Can't rename node. Node already exists.", VFSError::NODE_ALREADY_EXISTS);
}
else
throw CVFSException("Can't rename node. Node doesn't exists.", VFSError::NODE_DOESNT_EXISTS);
}
/**
* @brief Moves a node.
*
* @param From: The node to move.
* @param To: Desitination of the node.
*
* @throw Throws a CVFSException on error.
*/
void Move(const std::string &From, const std::string &To)
{
if(!NodeExists(From))
throw CVFSException("Can't move node. Source node doesn't exists.", VFSError::NODE_DOESNT_EXISTS);
if(!NodeExists(To))
throw CVFSException("Can't move node. Destination node doesn't exists.", VFSError::NODE_DOESNT_EXISTS);
auto DestNode = GetNodeInfo(To);
if(!DestNode->IsDir())
throw CVFSException("Can't move node. Destination node is a file.", VFSError::NODE_IS_FILE);
auto node = GetNodeInfo(From);
auto SrcParent = std::static_pointer_cast<CVFSDir>(GetNodeInfo(ExtractPath(From)));
auto DestParent = std::static_pointer_cast<CVFSDir>(DestNode);
SrcParent->RemoveChild(node->Name());
DestParent->AppendChild(node);
}
/**
* @brief Deletes a node.
*
* @throw Throws a CVFSException on error.
*/
void Delete(const std::string &Path)
{
if(!NodeExists(Path))
throw CVFSException("Can't delete node. Node doesn't exists.", VFSError::NODE_DOESNT_EXISTS);
auto node = GetNodeInfo(Path);
auto Parent = std::static_pointer_cast<CVFSDir>(GetNodeInfo(ExtractPath(Path)));
Parent->RemoveChild(node->Name());
}
/**
* @brief Copies a node.
*
* @param From: The node to copy.
* @param To: Desitination of the copy.
*
* @throw Throws a CVFSException on error.
*/
void Copy(const std::string &From, const std::string &To)
{
if(!NodeExists(From))
throw CVFSException("Can't copy node. Source node doesn't exists.", VFSError::NODE_DOESNT_EXISTS);
if(NodeExists(To))
throw CVFSException("Can't copy node. Destination node already exists.", VFSError::NODE_ALREADY_EXISTS);
auto DestNode = GetNodeInfo(ExtractPath(To));
if(!DestNode->IsDir())
throw CVFSException("Can't copy node. Destination node parent is a file.", VFSError::NODE_IS_FILE);
auto node = GetNodeInfo(From);
auto DestParent = std::static_pointer_cast<CVFSDir>(DestNode);
auto copy = node->Copy();
copy->m_Name = ExtractName(To);
DestParent->AppendChild(copy);
}
/**
* @return Returns the complete filesystem as stream.
*
* @attention This function allocates new memory for saving the filesystem.
* @throw Throws a CVFSException on out of memory.
*/
std::vector<char> Serialize()
{
try
{
VFSFile Disk = VFSFile(new CVFSFile("stream"));
Disk->Clear();
Disk->Write(MAGIC.data(), MAGIC.size());
uint64_t Entries = m_Root->GetChilds().size();
Disk->Write((char*)&Entries, sizeof(Entries));
FillSpace(Disk.get(), DISK_CHUNK_SIZE - (MAGIC.size() + sizeof(Entries)));
auto Childs = m_Root->GetChilds();
for (auto e : Childs)
SerializeNode(Disk.get(), e.get());
std::vector<char> Ret;
Ret.resize(Disk->Size());
Disk->Read(&Ret[0], Disk->Size(), 0);
return Ret;
}
catch(const std::bad_alloc &e)
{
throw CVFSException("Can't create stream. Out of mem. bad_alloc: " + std::string(e.what()), VFSError::OUT_OF_MEM);
}
}
/**
* @return Returns the complete filesystem as stream.
*
* @attention This function allocates new memory for saving the filesystem.
* @throw Throws a CVFSException on out of memory.
*/
void Deserialize(const std::vector<char> &Data)
{
try
{
size_t Pos = 0;
uint64_t Entries = 0;
std::string FileMagic;
FileMagic.resize(MAGIC.size());
ReadVector(Data, &FileMagic[0], FileMagic.size(), Pos);
if(FileMagic != MAGIC)
throw CVFSException("Can't create filesystem.", VFSError::CANT_CREATE_FILESYSTEM);
ReadVector(Data, (char*)&Entries, sizeof(Entries), Pos);
//Skips the sector.
Pos += (DISK_CHUNK_SIZE - (MAGIC.size() + sizeof(Entries)));
for (size_t i = 0; i < Entries; i++)
m_Root->AppendChild(DeserializeNode(Data, Pos));
// SerializeNode(Disk.get(), m_Root.get());
}
catch(const std::bad_alloc &e)
{
throw CVFSException("Can't create filesystem. Out of mem. bad_alloc: " + std::string(e.what()), VFSError::OUT_OF_MEM);
}
}
size_t ReadVector(const std::vector<char> &Data, char *Buf, size_t Size, size_t &Pos)
{
size_t CopyCount = (Pos + Size) < Data.size() ? Size : (Data.size() - Pos);
if(CopyCount > Data.size())
throw CVFSException("Can't create filesystem.", VFSError::FAILED_TO_READ_STREAM);
memcpy(Buf, Data.data() + Pos, CopyCount);
Pos += CopyCount;
return CopyCount;
}
~CVFS() {}
private:
const std::string MAGIC = "CVFS-DISK";
const int DISK_CHUNK_SIZE = 128;
const std::string NODE_IDENTIFIER = "NODE";
class CVFSFile;
class CVFSDir;
using VFSFile = std::shared_ptr<CVFSFile>;
using VFSDir = std::shared_ptr<CVFSDir>;
class CVFSFile : public CVFSNode
{
friend CVFS;
public:
CVFSFile() : CVFSNode()
{
m_IsDir = false;
m_Modified = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
m_Size = 0;
}
CVFSFile(const std::string &Name) : CVFSFile()
{
m_Name = Name;
}
CVFSFile(const CVFSFile &file) : CVFSNode(file)
{
m_Modified = file.m_Modified;
m_Size = file.m_Size;
ReserveChunks(file.m_Data.size());
//Copies the data content.
for (size_t i = 0; i < file.m_Data.size(); i++)
{
Chunk s = file.m_Data[i];
Chunk d = m_Data[i];
d->Filled = s->Filled;
memcpy(d->Data, s->Data, s->Filled);
}
}
/**
* @brief Clears the file.
*/
void Clear()
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
m_Data.clear();
ReserveChunks(4);
}
/**
* @brief Writes data to the file.
*
* @param Data: Data to write.
* @param Size: Size of the data.
*
* @return Returns the size which was written.
*/
size_t Write(const char *Data, size_t Size)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
//Calculates the chunk count which is needed to save the data.
size_t ChunkCount = Size / CHUNK_SIZE + ((Size % CHUNK_SIZE > 0) ? 1 : 0);
if(((m_Size + Size) >= (m_Data.size() * CHUNK_SIZE))) //Allocate new chunks, if we are exhausted.
ReserveChunks(ChunkCount);
size_t Written = 0;
size_t ChunkPos = m_Size / CHUNK_SIZE; //Calculates the beginning chunk.
while (Written < Size)
{
Chunk c = m_Data[ChunkPos];
size_t Free = c->Size - c->Filled;
size_t CopyCount = ((Size - Written) >= Free) ? Free : (Size - Written); //Calculate the right copy size.
memcpy(c->Data + c->Filled, Data + Written, CopyCount);
c->Filled += CopyCount; //Chunk update
m_Size += CopyCount;
Written += CopyCount;
ChunkPos++;
}
m_Modified = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return Written;
}
/**
* @brief Reads data from the file.
*
* @param Buf: Buffer which receives the data.
* @param Size: Size of the buffer.
* @param CurPos: Position of inside the file.
*
* @return Returns the size which was readed.
*/
size_t Read(char *Buf, size_t Size, size_t CurPos)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
size_t ChunkPos = CurPos / CHUNK_SIZE; //Calculates the beginning chunk.
size_t Readed = 0;
while (Readed < Size)
{
if(ChunkPos >= m_Data.size())
break;
Chunk c = m_Data[ChunkPos];
size_t Pos = CurPos - ChunkPos * CHUNK_SIZE;
Pos = (Pos > CHUNK_SIZE) ? 0 : Pos;
int CopyCount = c->Filled - Pos;
CopyCount = CopyCount > Size ? Size : CopyCount; //Calculate the right copy size.
if(CopyCount <= 0)
break;
memcpy(Buf + Readed, c->Data + Pos, CopyCount);
Readed += CopyCount;
ChunkPos++;
}
m_Accessed = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return Readed;
}
/**
* @return Returns the last modification time.
*/
inline time_t Modified() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_Modified;
}
inline size_t Size() const
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
return m_Size;
}
/**
* @return Returns a copy of this node.
*/
VFSNode Copy() override
{
return VFSFile(new CVFSFile(*this));
}
private:
/**
* Data chunk.
*/
struct SChunk
{
public:
SChunk()
{
Size = CHUNK_SIZE;
Filled = 0;
Data = new char[Size];
}
int Size;
int Filled;
char *Data;
~SChunk()
{
delete[] Data;
}
};
using Chunk = std::shared_ptr<SChunk>;
/**
* @brief Reserves new space for data.
*
* @param Count: Chunks to allocate.
*/
void ReserveChunks(size_t Count)
{
m_Data.reserve(Count);
for (size_t i = 0; i < Count; i++)
m_Data.push_back(Chunk(new SChunk()));
}
time_t m_Modified;
size_t m_Size;
std::vector<Chunk> m_Data;
};
class CVFSDir : public CVFSNode
{
public:
CVFSDir() : CVFSNode()
{
m_IsDir = true;
}
CVFSDir(const std::string &Name) : CVFSDir()
{
m_Name = Name;
}
CVFSDir(const CVFSDir &dir) : CVFSNode(dir)
{
m_Childs.reserve(dir.m_Childs.size());
for (auto &&e : dir.m_Childs)
{
m_Childs.push_back(e->Copy());
}
}
/**
* @brief Adds a new child to this directory.
*
* @param Child: A file or dir to add.
*/
void AppendChild(VFSNode Child)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
InternalAppendChild(Child);
}
/**
* @brief Searches for a node.
*
* @param Name: Name of the node.
*
* @return Returns the node of null if the node wasn't found.
*/
VFSNode Search(const std::string &Name)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
VFSNode Ret;
if(!m_Childs.empty())
{
size_t Pos = Search(Name, 0, m_Childs.size() - 1);
if(m_Childs[Pos]->Name() == Name)
Ret = m_Childs[Pos];
}
return Ret;
}
/**
* @brief Renames and reorders a child.
*
* @param Name: Current name of the child.
* @param NewName: New name of the child.
*/
void RenameChild(const std::string &Name, const std::string &NewName)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
size_t Pos = Search(Name, 0, m_Childs.size() - 1);
auto Child = m_Childs[Pos];
if(Child->Name() == Name)
{
m_Childs.erase(m_Childs.begin() + Pos); //Removes the child temporary.
Child->m_Name = NewName;
InternalAppendChild(Child);
}
}
/**
* @brief Removes a child.
*
* @param Name: Name of the child.
*/
void RemoveChild(const std::string &Name)
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
size_t Pos = Search(Name, 0, m_Childs.size() - 1);
auto Child = m_Childs[Pos];
if(Child->Name() == Name)
m_Childs.erase(m_Childs.begin() + Pos); //Removes the child.
}
/**
* @return Returns all childs of this dir.
*/
std::vector<VFSNode> GetChilds()
{
std::lock_guard<std::mutex> lock(m_UpdateLock);
m_Accessed = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return m_Childs;
}
/**
* @return Returns a copy of this node.
*/
VFSNode Copy() override
{
return VFSDir(new CVFSDir(*this));
}
private:
/**
* @brief Binary search for faster searches.
*
* @param Name: Name of the node to find.
* @param Start: Start of the frame.
* @param End: End of the frame.
*
* @return Returns the position of the node.
*/
size_t Search(const std::string &Name, size_t Start, size_t End)
{
if(End < Start || End == (size_t) -1)
return 0;
else if(End == Start)
return End;
size_t Middle = Start + (End - Start) / 2;
std::string PosName = m_Childs[Middle]->Name();
if(PosName == Name)
return Middle;
else if(Name > PosName)
return Search(Name, Middle + 1, End);
else if(Name < PosName)
return Search(Name, Start, Middle - 1);
return Middle;
}
/**
* @brief Adds a new child to this directory.
*
* @param Child: A file or dir to add.
*/
void InternalAppendChild(VFSNode Child)
{
size_t Pos = 0;
//Sorts the data ascending.
for (Pos = 0; Pos < m_Childs.size(); Pos++)
{
if(Child->Name() < m_Childs[Pos]->Name())
break;
}
m_Childs.insert(m_Childs.begin() + Pos, Child);
}
std::vector<VFSNode> m_Childs;
};
/**
* @brief Splits into a list of names.
*
* @param Path: Path to split.
*
* @return Returns the path as list.
*/
std::vector<std::string> SplitPath(const std::string &Path)
{
size_t Pos = 0;
std::vector<std::string> Ret;
//Ignores the first '/' if it exitst.
if(!Path.empty() && Path[0] == '/')
Pos++;
while (Pos != std::string::npos)
{
size_t Start = Pos;
Pos = Path.find('/', Start);
std::string Dir = Path.substr(Start, Pos - Start);
if(!Dir.empty())
Ret.push_back(Dir);
if(Pos != std::string::npos)
Pos++;
}
return Ret;
}
/**
* @return Returns a path without the last child e.g Path: /test/test.txt -> ret: /test
*/
std::string ExtractPath(const std::string &Path)
{
size_t Pos = Path.find_last_of("/");
if(Pos == Path.length() - 1)
Pos = Path.find_last_of("/", Pos - 1);
return Path.substr(0, Pos);
}
/**
* @return Returns the name of the last child
*/
std::string ExtractName(const std::string &Path)
{
size_t End = std::string::npos;
size_t Pos = Path.find_last_of("/");
if(Pos == Path.length() - 1)
{
End = Pos - 1;
Pos = Path.find_last_of("/", Pos - 1);
}
return Path.substr(Pos + 1, End - Pos);
}
/**
* @brief Fills in padding bytes inside the file.
*/
void FillSpace(CVFSFile *file, size_t Count)
{
for (size_t i = 0; i < Count; i++)
{
char c = 0;
file->Write(&c, sizeof(c));
}
}
void SerializeNode(CVFSFile *file, CVFSNode *Node)
{
size_t NodeSize = NODE_IDENTIFIER.size() + sizeof(int) + (int)Node->m_Name.size() + sizeof(Node->m_IsDir) + sizeof(Node->m_Created) + sizeof(Node->m_Accessed);
file->Write(NODE_IDENTIFIER.data(), NODE_IDENTIFIER.size());
//Writes all base node informations.
int NameSize = Node->m_Name.size();
file->Write((char*)&NameSize, sizeof(int));
file->Write(Node->m_Name.data(), NameSize);
file->Write((char*)&Node->m_IsDir, sizeof(Node->m_IsDir));
file->Write((char*)&Node->m_Created, sizeof(Node->m_Created));
file->Write((char*)&Node->m_Accessed, sizeof(Node->m_Accessed));
if(Node->IsDir())
{
auto Dir = static_cast<CVFSDir*>(Node);
auto Childs = Dir->GetChilds();
//Adds the count of entries.
uint64_t EntryCount = Childs.size();
file->Write((char*)&EntryCount, sizeof(EntryCount));
int FillSize = DISK_CHUNK_SIZE - (NodeSize + sizeof(uint64_t));
FillSpace(file, FillSize);
for (auto e : Childs)
SerializeNode(file, e.get());
}
else
{
auto NodeFile = static_cast<CVFSFile*>(Node);
time_t mtime = NodeFile->Modified();
file->Write((char*)&mtime, sizeof(mtime));
uint64_t Size = NodeFile->Size();
file->Write((char*)&Size, sizeof(Size));
NodeSize += sizeof(mtime) + sizeof(Size);
//If the data fits into the chunk, write it into the current chunk.
int FillSize = DISK_CHUNK_SIZE - (NodeSize > DISK_CHUNK_SIZE ? (NodeSize - DISK_CHUNK_SIZE) : NodeSize);
if(NodeFile->Size() <= FillSize)
{
file->Write(NodeFile->m_Data[0]->Data, NodeFile->m_Data[0]->Filled);
FillSize -= NodeFile->Size();
}