fileStream.cpp 19 KB

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