Counter Strike : Global Offensive Source Code
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.

118 lines
2.2 KiB

  1. //====== Copyright c 1996-2007, 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 + 1, 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. pData->m_data[nSize] = '\0';
  34. fclose( f );
  35. }
  36. return pData;
  37. }
  38. void CachedFileData::Free( void )
  39. {
  40. free( this );
  41. }
  42. CachedFileData *CachedFileData::GetByDataPtr( void const *pvDataPtr )
  43. {
  44. unsigned char const *pbBuffer = reinterpret_cast< unsigned char const * >( pvDataPtr );
  45. // Assert( pbBuffer );
  46. CachedFileData const *pData = reinterpret_cast< CachedFileData const * >( pbBuffer - eHeaderSize );
  47. // Assert( pData->m_signature == s_ulCachedFileSignature );
  48. return const_cast< CachedFileData * >( pData );
  49. }
  50. char const * CachedFileData::GetFileName() const
  51. {
  52. return m_chFilename;
  53. }
  54. void const * CachedFileData::GetDataPtr() const
  55. {
  56. return m_data;
  57. }
  58. int CachedFileData::GetDataLen() const
  59. {
  60. return MAX( m_numDataBytes, 0 );
  61. }
  62. bool CachedFileData::IsValid() const
  63. {
  64. return ( m_numDataBytes >= 0 );
  65. }
  66. //
  67. // File cache implementation
  68. //
  69. FileCache::FileCache()
  70. {
  71. NULL;
  72. }
  73. CachedFileData * FileCache::Get( char const *szFilename )
  74. {
  75. // Search the cache first
  76. Mapping::iterator it = m_map.find( szFilename );
  77. if ( it != m_map.end() )
  78. return it->second;
  79. // Create the cached file data
  80. CachedFileData *pData = CachedFileData::Create( szFilename );
  81. if ( pData )
  82. m_map.insert( Mapping::value_type( pData->GetFileName(), pData ) );
  83. return pData;
  84. }
  85. void FileCache::Clear()
  86. {
  87. for ( Mapping::iterator it = m_map.begin(), itEnd = m_map.end(); it != itEnd; ++ it )
  88. {
  89. it->second->Free();
  90. }
  91. m_map.clear();
  92. }