fileStream.cpp 19 KB

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