1 // Copyright (C) 2002-2012 Nikolaus Gebhardt
2 // This file is part of the "Irrlicht Engine".
3 // For conditions of distribution and use, see copyright notice in irrlicht.h
4 
5 #include "CMemoryFile.h"
6 #include "irrString.h"
7 
8 namespace irr
9 {
10 namespace io
11 {
12 
13 
CMemoryFile(void * memory,long len,const io::path & fileName,bool d)14 CMemoryFile::CMemoryFile(void* memory, long len, const io::path& fileName, bool d)
15 : Buffer(memory), Len(len), Pos(0), Filename(fileName), deleteMemoryWhenDropped(d)
16 {
17 	#ifdef _DEBUG
18 	setDebugName("CMemoryFile");
19 	#endif
20 }
21 
22 
~CMemoryFile()23 CMemoryFile::~CMemoryFile()
24 {
25 	if (deleteMemoryWhenDropped)
26 		delete [] (c8*)Buffer;
27 }
28 
29 
30 //! returns how much was read
read(void * buffer,u32 sizeToRead)31 s32 CMemoryFile::read(void* buffer, u32 sizeToRead)
32 {
33 	s32 amount = static_cast<s32>(sizeToRead);
34 	if (Pos + amount > Len)
35 		amount -= Pos + amount - Len;
36 
37 	if (amount <= 0)
38 		return 0;
39 
40 	c8* p = (c8*)Buffer;
41 	memcpy(buffer, p + Pos, amount);
42 
43 	Pos += amount;
44 
45 	return amount;
46 }
47 
48 //! returns how much was written
write(const void * buffer,u32 sizeToWrite)49 s32 CMemoryFile::write(const void* buffer, u32 sizeToWrite)
50 {
51 	s32 amount = static_cast<s32>(sizeToWrite);
52 	if (Pos + amount > Len)
53 		amount -= Pos + amount - Len;
54 
55 	if (amount <= 0)
56 		return 0;
57 
58 	c8* p = (c8*)Buffer;
59 	memcpy(p + Pos, buffer, amount);
60 
61 	Pos += amount;
62 
63 	return amount;
64 }
65 
66 
67 
68 //! changes position in file, returns true if successful
69 //! if relativeMovement==true, the pos is changed relative to current pos,
70 //! otherwise from begin of file
seek(long finalPos,bool relativeMovement)71 bool CMemoryFile::seek(long finalPos, bool relativeMovement)
72 {
73 	if (relativeMovement)
74 	{
75 		if (Pos + finalPos > Len)
76 			return false;
77 
78 		Pos += finalPos;
79 	}
80 	else
81 	{
82 		if (finalPos > Len)
83 			return false;
84 
85 		Pos = finalPos;
86 	}
87 
88 	return true;
89 }
90 
91 
92 //! returns size of file
getSize() const93 long CMemoryFile::getSize() const
94 {
95 	return Len;
96 }
97 
98 
99 //! returns where in the file we are.
getPos() const100 long CMemoryFile::getPos() const
101 {
102 	return Pos;
103 }
104 
105 
106 //! returns name of file
getFileName() const107 const io::path& CMemoryFile::getFileName() const
108 {
109 	return Filename;
110 }
111 
112 
createMemoryReadFile(void * memory,long size,const io::path & fileName,bool deleteMemoryWhenDropped)113 IReadFile* createMemoryReadFile(void* memory, long size, const io::path& fileName, bool deleteMemoryWhenDropped)
114 {
115 	CMemoryFile* file = new CMemoryFile(memory, size, fileName, deleteMemoryWhenDropped);
116 	return file;
117 }
118 
119 
120 } // end namespace io
121 } // end namespace irr
122 
123