Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
2.2 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. #include "filememcache.h"
  9. namespace {
  10. unsigned long s_ulCachedFileSignature = 0xCACEF11E;
  11. };
  12. //
  13. // Cached file data implementation
  14. //
  15. CachedFileData * CachedFileData::Create( char const *szFilename )
  16. {
  17. FILE *f = fopen( szFilename, "rb" );
  18. int nSize = -1;
  19. if ( f )
  20. {
  21. fseek( f, 0, SEEK_END );
  22. nSize = ftell( f );
  23. fseek( f, 0, SEEK_SET );
  24. }
  25. CachedFileData *pData = ( CachedFileData * ) malloc( eHeaderSize + max( nSize, 0 ) );
  26. strcpy( pData->m_chFilename, szFilename );
  27. pData->m_numRefs = 0;
  28. pData->m_numDataBytes = nSize;
  29. pData->m_signature = s_ulCachedFileSignature;
  30. if ( f )
  31. {
  32. fread( pData->m_data, 1, nSize, f );
  33. fclose( f );
  34. }
  35. return pData;
  36. }
  37. void CachedFileData::Free( void )
  38. {
  39. free( this );
  40. }
  41. CachedFileData *CachedFileData::GetByDataPtr( void const *pvDataPtr )
  42. {
  43. unsigned char const *pbBuffer = reinterpret_cast< unsigned char const * >( pvDataPtr );
  44. // Assert( pbBuffer );
  45. CachedFileData const *pData = reinterpret_cast< CachedFileData const * >( pbBuffer - eHeaderSize );
  46. // Assert( pData->m_signature == s_ulCachedFileSignature );
  47. return const_cast< CachedFileData * >( pData );
  48. }
  49. char const * CachedFileData::GetFileName() const
  50. {
  51. return m_chFilename;
  52. }
  53. void const * CachedFileData::GetDataPtr() const
  54. {
  55. return m_data;
  56. }
  57. int CachedFileData::GetDataLen() const
  58. {
  59. return max( m_numDataBytes, 0 );
  60. }
  61. bool CachedFileData::IsValid() const
  62. {
  63. return ( m_numDataBytes >= 0 );
  64. }
  65. //
  66. // File cache implementation
  67. //
  68. FileCache::FileCache()
  69. {
  70. NULL;
  71. }
  72. CachedFileData * FileCache::Get( char const *szFilename )
  73. {
  74. // Search the cache first
  75. Mapping::iterator it = m_map.find( szFilename );
  76. if ( it != m_map.end() )
  77. return it->second;
  78. // Create the cached file data
  79. CachedFileData *pData = CachedFileData::Create( szFilename );
  80. if ( pData )
  81. m_map.insert( Mapping::value_type( pData->GetFileName(), pData ) );
  82. return pData;
  83. }
  84. void FileCache::Clear()
  85. {
  86. for ( Mapping::iterator it = m_map.begin(), itEnd = m_map.end(); it != itEnd; ++ it )
  87. {
  88. it->second->Free();
  89. }
  90. m_map.clear();
  91. }