fileStream.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "core/stream/fileStream.h"
  24. //-----------------------------------------------------------------------------
  25. // FileStream methods...
  26. //-----------------------------------------------------------------------------
  27. //-----------------------------------------------------------------------------
  28. FileStream::FileStream()
  29. {
  30. dMemset(mBuffer, 0, sizeof(mBuffer));
  31. // initialize the file stream
  32. init();
  33. }
  34. FileStream *FileStream::createAndOpen(const String &inFileName, Torque::FS::File::AccessMode inMode)
  35. {
  36. FileStream *newStream = new FileStream;
  37. bool success = newStream->open( inFileName, inMode );
  38. if ( !success )
  39. {
  40. delete newStream;
  41. newStream = NULL;
  42. }
  43. return newStream;
  44. }
  45. //-----------------------------------------------------------------------------
  46. FileStream::~FileStream()
  47. {
  48. // make sure the file stream is closed
  49. close();
  50. }
  51. //-----------------------------------------------------------------------------
  52. bool FileStream::hasCapability(const Capability i_cap) const
  53. {
  54. return(0 != (U32(i_cap) & mStreamCaps));
  55. }
  56. //-----------------------------------------------------------------------------
  57. U32 FileStream::getPosition() const
  58. {
  59. AssertFatal(0 != mStreamCaps, "FileStream::getPosition: the stream isn't open");
  60. //AssertFatal(true == hasCapability(StreamPosition), "FileStream::getPosition(): lacks positioning capability");
  61. // return the position inside the buffer if its valid, otherwise return the underlying file position
  62. return((BUFFER_INVALID != mBuffHead) ? mBuffPos : mFile->getPosition());
  63. }
  64. //-----------------------------------------------------------------------------
  65. bool FileStream::setPosition(const U32 i_newPosition)
  66. {
  67. AssertFatal(0 != mStreamCaps, "FileStream::setPosition: the stream isn't open");
  68. AssertFatal(hasCapability(StreamPosition), "FileStream::setPosition: lacks positioning capability");
  69. // if the buffer is valid, test the new position against the bounds of the buffer
  70. if ((BUFFER_INVALID != mBuffHead) && (i_newPosition >= mBuffHead) && (i_newPosition <= mBuffTail))
  71. {
  72. // set the position and return
  73. mBuffPos = i_newPosition;
  74. // FIXME [tom, 9/5/2006] This needs to be checked. Basically, when seeking within
  75. // the buffer, if the stream has an EOS status before the seek then if you try to
  76. // read immediately after seeking, you'll incorrectly get an EOS.
  77. //
  78. // I am not 100% sure if this fix is correct, but it seems to be working for the undo system.
  79. if(mBuffPos < mBuffTail)
  80. Stream::setStatus(Ok);
  81. return(true);
  82. }
  83. // otherwise the new position lies in some block not in memory
  84. else
  85. {
  86. if (mDirty)
  87. flush();
  88. clearBuffer();
  89. mFile->setPosition(i_newPosition, Torque::FS::File::Begin);
  90. setStatus();
  91. if (mFile->getStatus() == Torque::FS::FileNode::EndOfFile)
  92. mEOF = true;
  93. return(Ok == getStatus() || EOS == getStatus());
  94. }
  95. }
  96. //-----------------------------------------------------------------------------
  97. U32 FileStream::getStreamSize()
  98. {
  99. AssertWarn(0 != mStreamCaps, "FileStream::getStreamSize: the stream isn't open");
  100. AssertFatal((BUFFER_INVALID != mBuffHead && true == mDirty) || false == mDirty, "FileStream::getStreamSize: buffer must be valid if its dirty");
  101. // the stream size may not match the size on-disk if its been written to...
  102. if (mDirty)
  103. return(getMax((U32)(mFile->getSize()), mBuffTail + 1)); ///<@todo U64 vs U32 issue
  104. // otherwise just get the size on disk...
  105. else
  106. return(mFile->getSize());
  107. }
  108. //-----------------------------------------------------------------------------
  109. bool FileStream::open(const String &inFileName, Torque::FS::File::AccessMode inMode)
  110. {
  111. AssertWarn(0 == mStreamCaps, "FileStream::setPosition: the stream is already open");
  112. AssertFatal(inFileName.isNotEmpty(), "FileStream::open: empty filename");
  113. // make sure the file stream's state is clean
  114. clearBuffer();
  115. Torque::Path filePath(inFileName);
  116. // IF we are writing, make sure the path exists
  117. if( inMode == Torque::FS::File::Write || inMode == Torque::FS::File::WriteAppend || inMode == Torque::FS::File::ReadWrite )
  118. Torque::FS::CreatePath(filePath);
  119. mFile = Torque::FS::OpenFile(filePath, inMode);
  120. if (mFile != NULL)
  121. {
  122. setStatus();
  123. switch (inMode)
  124. {
  125. case Torque::FS::File::Read:
  126. mStreamCaps = U32(StreamRead) |
  127. U32(StreamPosition);
  128. break;
  129. case Torque::FS::File::Write:
  130. case Torque::FS::File::WriteAppend:
  131. mStreamCaps = U32(StreamWrite) |
  132. U32(StreamPosition);
  133. break;
  134. case Torque::FS::File::ReadWrite:
  135. mStreamCaps = U32(StreamRead) |
  136. U32(StreamWrite) |
  137. U32(StreamPosition);
  138. break;
  139. default:
  140. AssertFatal(false, String::ToString( "FileStream::open: bad access mode on %s", inFileName.c_str() ));
  141. }
  142. }
  143. else
  144. {
  145. Stream::setStatus(IOError);
  146. return(false);
  147. }
  148. return getStatus() == Ok;
  149. }
  150. //-----------------------------------------------------------------------------
  151. void FileStream::close()
  152. {
  153. if (getStatus() == Closed)
  154. return;
  155. if (mFile != NULL )
  156. {
  157. // make sure nothing in the buffer differs from what is on disk
  158. if (mDirty)
  159. flush();
  160. // and close the file
  161. mFile->close();
  162. AssertFatal(mFile->getStatus() == Torque::FS::FileNode::Closed, "FileStream::close: close failed");
  163. mFile = NULL;
  164. }
  165. // clear the file stream's state
  166. init();
  167. }
  168. //-----------------------------------------------------------------------------
  169. bool FileStream::flush()
  170. {
  171. AssertWarn(0 != mStreamCaps, "FileStream::flush: the stream isn't open");
  172. AssertFatal(false == mDirty || BUFFER_INVALID != mBuffHead, "FileStream::flush: buffer must be valid if its dirty");
  173. // if the buffer is dirty
  174. if (mDirty)
  175. {
  176. AssertFatal(hasCapability(StreamWrite), "FileStream::flush: a buffer without write-capability should never be dirty");
  177. // align the file pointer to the buffer head
  178. if (mBuffHead != mFile->getPosition())
  179. {
  180. mFile->setPosition(mBuffHead, Torque::FS::File::Begin);
  181. if (mFile->getStatus() != Torque::FS::FileNode::Open && mFile->getStatus() != Torque::FS::FileNode::EndOfFile)
  182. return(false);
  183. }
  184. // write contents of the buffer to disk
  185. U32 blockHead;
  186. calcBlockHead(mBuffHead, &blockHead);
  187. mFile->write((char *)mBuffer + (mBuffHead - blockHead), mBuffTail - mBuffHead + 1);
  188. // and update the file stream's state
  189. setStatus();
  190. if (EOS == getStatus())
  191. mEOF = true;
  192. if (Ok == getStatus() || EOS == getStatus())
  193. // and update the status of the buffer
  194. mDirty = false;
  195. else
  196. return(false);
  197. }
  198. return(true);
  199. }
  200. //-----------------------------------------------------------------------------
  201. bool FileStream::_read(const U32 i_numBytes, void *o_pBuffer)
  202. {
  203. AssertFatal(0 != mStreamCaps, "FileStream::_read: the stream isn't open");
  204. AssertFatal(NULL != o_pBuffer || i_numBytes == 0, "FileStream::_read: NULL destination pointer with non-zero read request");
  205. if (!hasCapability(Stream::StreamRead))
  206. {
  207. AssertFatal(false, "FileStream::_read: file stream lacks capability");
  208. Stream::setStatus(IllegalCall);
  209. return(false);
  210. }
  211. // exit on pre-existing errors
  212. if (Ok != getStatus())
  213. return(false);
  214. // if a request of non-zero length was made
  215. if (0 != i_numBytes)
  216. {
  217. U8 *pDst = (U8 *)o_pBuffer;
  218. U32 readSize;
  219. U32 remaining = i_numBytes;
  220. U32 bytesRead;
  221. U32 blockHead;
  222. U32 blockTail;
  223. // check if the buffer has some data in it
  224. if (BUFFER_INVALID != mBuffHead)
  225. {
  226. // copy as much as possible from the buffer into the destination
  227. readSize = ((mBuffTail + 1) >= mBuffPos) ? (mBuffTail + 1 - mBuffPos) : 0;
  228. readSize = getMin(readSize, remaining);
  229. calcBlockHead(mBuffPos, &blockHead);
  230. dMemcpy(pDst, mBuffer + (mBuffPos - blockHead), readSize);
  231. // reduce the remaining amount to read
  232. remaining -= readSize;
  233. // advance the buffer pointers
  234. mBuffPos += readSize;
  235. pDst += readSize;
  236. if (mBuffPos > mBuffTail && remaining != 0)
  237. {
  238. flush();
  239. mBuffHead = BUFFER_INVALID;
  240. if (mEOF == true)
  241. Stream::setStatus(EOS);
  242. }
  243. }
  244. // if the request wasn't satisfied by the buffer and the file has more data
  245. if (false == mEOF && 0 < remaining)
  246. {
  247. // flush the buffer if its dirty, since we now need to go to disk
  248. if (true == mDirty)
  249. flush();
  250. // make sure we know the current read location in the underlying file
  251. mBuffPos = mFile->getPosition();
  252. calcBlockBounds(mBuffPos, &blockHead, &blockTail);
  253. // check if the data to be read falls within a single block
  254. if ((mBuffPos + remaining) <= blockTail)
  255. {
  256. // fill the buffer from disk
  257. if (true == fillBuffer(mBuffPos))
  258. {
  259. // copy as much as possible from the buffer to the destination
  260. remaining = getMin(remaining, mBuffTail - mBuffPos + 1);
  261. dMemcpy(pDst, mBuffer + (mBuffPos - blockHead), remaining);
  262. // advance the buffer pointer
  263. mBuffPos += remaining;
  264. }
  265. else
  266. return(false);
  267. }
  268. // otherwise the remaining spans multiple blocks
  269. else
  270. {
  271. clearBuffer();
  272. // read from disk directly into the destination
  273. bytesRead = mFile->read((char *)pDst, remaining);
  274. setStatus();
  275. // check to make sure we read as much as expected
  276. if (Ok == getStatus() || EOS == getStatus())
  277. {
  278. // if not, update the end-of-file status
  279. if (0 != bytesRead && EOS == getStatus())
  280. {
  281. Stream::setStatus(Ok);
  282. mEOF = true;
  283. }
  284. }
  285. else
  286. return(false);
  287. }
  288. }
  289. }
  290. return(true);
  291. }
  292. //-----------------------------------------------------------------------------
  293. bool FileStream::_write(const U32 i_numBytes, const void *i_pBuffer)
  294. {
  295. AssertFatal(0 != mStreamCaps, "FileStream::_write: the stream isn't open");
  296. AssertFatal(NULL != i_pBuffer || i_numBytes == 0, "FileStream::_write: NULL source buffer pointer on non-zero write request");
  297. if (!hasCapability(Stream::StreamWrite))
  298. {
  299. AssertFatal(false, "FileStream::_write: file stream lacks capability");
  300. Stream::setStatus(IllegalCall);
  301. return(false);
  302. }
  303. // exit on pre-existing errors
  304. if (Ok != getStatus() && EOS != getStatus())
  305. return(false);
  306. // if a request of non-zero length was made
  307. if (0 != i_numBytes)
  308. {
  309. U8 *pSrc = (U8 *)i_pBuffer;
  310. U32 writeSize;
  311. U32 remaining = i_numBytes;
  312. U32 bytesWrit;
  313. U32 blockHead;
  314. U32 blockTail;
  315. // check if the buffer is valid
  316. if (BUFFER_INVALID != mBuffHead)
  317. {
  318. // copy as much as possible from the source to the buffer
  319. calcBlockBounds(mBuffHead, &blockHead, &blockTail);
  320. writeSize = (mBuffPos > blockTail) ? 0 : blockTail - mBuffPos + 1;
  321. writeSize = getMin(writeSize, remaining);
  322. AssertFatal(0 == writeSize || (mBuffPos - blockHead) < BUFFER_SIZE, "FileStream::_write: out of bounds buffer position");
  323. dMemcpy(mBuffer + (mBuffPos - blockHead), pSrc, writeSize);
  324. // reduce the remaining amount to be written
  325. remaining -= writeSize;
  326. // advance the buffer pointers
  327. mBuffPos += writeSize;
  328. mBuffTail = getMax(mBuffTail, mBuffPos - 1);
  329. pSrc += writeSize;
  330. // mark the buffer dirty
  331. if (0 < writeSize)
  332. mDirty = true;
  333. }
  334. // if the request wasn't satisfied by the buffer
  335. if (0 < remaining)
  336. {
  337. // flush the buffer if its dirty, since we now need to go to disk
  338. if (mDirty)
  339. flush();
  340. // make sure we know the current write location in the underlying file
  341. mBuffPos = mFile->getPosition();
  342. calcBlockBounds(mBuffPos, &blockHead, &blockTail);
  343. // check if the data to be written falls within a single block
  344. if ((mBuffPos + remaining) <= blockTail)
  345. {
  346. // write the data to the buffer
  347. dMemcpy(mBuffer + (mBuffPos - blockHead), pSrc, remaining);
  348. // update the buffer pointers
  349. mBuffHead = mBuffPos;
  350. mBuffPos += remaining;
  351. mBuffTail = mBuffPos - 1;
  352. // mark the buffer dirty
  353. mDirty = true;
  354. }
  355. // otherwise the remaining spans multiple blocks
  356. else
  357. {
  358. clearBuffer();
  359. // write to disk directly from the source
  360. bytesWrit = mFile->write((char *)pSrc, remaining);
  361. setStatus();
  362. return(Ok == getStatus() || EOS == getStatus());
  363. }
  364. }
  365. }
  366. return(true);
  367. }
  368. //-----------------------------------------------------------------------------
  369. void FileStream::init()
  370. {
  371. mStreamCaps = 0;
  372. Stream::setStatus(Closed);
  373. clearBuffer();
  374. }
  375. //-----------------------------------------------------------------------------
  376. bool FileStream::fillBuffer(const U32 i_startPosition)
  377. {
  378. AssertFatal(0 != mStreamCaps, "FileStream::fillBuffer: the stream isn't open");
  379. AssertFatal(false == mDirty, "FileStream::fillBuffer: buffer must be clean to fill");
  380. // make sure start position and file pointer jive
  381. if (i_startPosition != mFile->getPosition())
  382. {
  383. mFile->setPosition(i_startPosition, Torque::FS::File::Begin);
  384. if (mFile->getStatus() != Torque::FS::FileNode::Open && mFile->getStatus() != Torque::FS::FileNode::EndOfFile)
  385. {
  386. setStatus();
  387. return(false);
  388. }
  389. else
  390. // update buffer pointer
  391. mBuffPos = i_startPosition;
  392. }
  393. // check if file pointer is at end-of-file
  394. if (EOS == getStatus())
  395. {
  396. // invalidate the buffer
  397. mBuffHead = BUFFER_INVALID;
  398. // set the status to end-of-stream
  399. mEOF = true;
  400. }
  401. // otherwise
  402. else
  403. {
  404. U32 blockHead;
  405. // locate bounds of buffer containing current position
  406. calcBlockHead(mBuffPos, &blockHead);
  407. // read as much as possible from input file
  408. U32 bytesRead = mFile->read((char *)mBuffer + (i_startPosition - blockHead), BUFFER_SIZE - (i_startPosition - blockHead));
  409. setStatus();
  410. if (Ok == getStatus() || EOS == getStatus())
  411. {
  412. // update buffer pointers
  413. mBuffHead = i_startPosition;
  414. mBuffPos = i_startPosition;
  415. mBuffTail = i_startPosition + bytesRead - 1;
  416. // update end-of-file status
  417. if (0 != bytesRead && EOS == getStatus())
  418. {
  419. Stream::setStatus(Ok);
  420. mEOF = true;
  421. }
  422. }
  423. else
  424. {
  425. mBuffHead = BUFFER_INVALID;
  426. return(false);
  427. }
  428. }
  429. return(true);
  430. }
  431. //-----------------------------------------------------------------------------
  432. void FileStream::clearBuffer()
  433. {
  434. mBuffHead = BUFFER_INVALID;
  435. mBuffPos = 0;
  436. mBuffTail = 0;
  437. mDirty = false;
  438. mEOF = false;
  439. }
  440. //-----------------------------------------------------------------------------
  441. void FileStream::calcBlockHead(const U32 i_position, U32 *o_blockHead)
  442. {
  443. AssertFatal(NULL != o_blockHead, "FileStream::calcBlockHead: NULL pointer passed for block head");
  444. *o_blockHead = i_position/BUFFER_SIZE * BUFFER_SIZE;
  445. }
  446. //-----------------------------------------------------------------------------
  447. void FileStream::calcBlockBounds(const U32 i_position, U32 *o_blockHead, U32 *o_blockTail)
  448. {
  449. AssertFatal(NULL != o_blockHead, "FileStream::calcBlockBounds: NULL pointer passed for block head");
  450. AssertFatal(NULL != o_blockTail, "FileStream::calcBlockBounds: NULL pointer passed for block tail");
  451. *o_blockHead = i_position/BUFFER_SIZE * BUFFER_SIZE;
  452. *o_blockTail = *o_blockHead + BUFFER_SIZE - 1;
  453. }
  454. //-----------------------------------------------------------------------------
  455. void FileStream::setStatus()
  456. {
  457. switch (mFile->getStatus())
  458. {
  459. case Torque::FS::FileNode::Open:
  460. Stream::setStatus(Ok);
  461. break;
  462. case Torque::FS::FileNode::Closed:
  463. Stream::setStatus(Closed);
  464. break;
  465. case Torque::FS::FileNode::EndOfFile:
  466. Stream::setStatus(EOS);
  467. break;
  468. case Torque::FS::FileNode::FileSystemFull:
  469. case Torque::FS::FileNode::NoSuchFile:
  470. case Torque::FS::FileNode::AccessDenied:
  471. case Torque::FS::FileNode::NoDisk:
  472. case Torque::FS::FileNode::SharingViolation:
  473. Stream::setStatus(IOError);
  474. break;
  475. case Torque::FS::FileNode::IllegalCall:
  476. Stream::setStatus(IllegalCall);
  477. break;
  478. case Torque::FS::FileNode::UnknownError:
  479. Stream::setStatus(UnknownError);
  480. break;
  481. default:
  482. AssertFatal(false, "FileStream::setStatus: invalid error mode");
  483. }
  484. }
  485. FileStream* FileStream::clone() const
  486. {
  487. Torque::FS::File::AccessMode mode;
  488. if( hasCapability( StreamWrite ) && hasCapability( StreamRead ) )
  489. mode = Torque::FS::File::ReadWrite;
  490. else if( hasCapability( StreamWrite ) )
  491. mode = Torque::FS::File::Write;
  492. else
  493. mode = Torque::FS::File::Read;
  494. FileStream* copy = createAndOpen( mFile->getName(), mode );
  495. if( copy && copy->setPosition( getPosition() ) )
  496. return copy;
  497. delete copy;
  498. return NULL;
  499. }