tb_file_posix.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #include "tb_system.h"
  6. #ifdef TB_FILE_POSIX
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <assert.h>
  10. namespace tb {
  11. TBFileExternalReaderFunction TBFile::reader_function = NULL;
  12. class TBMemoryFile : public TBFile
  13. {
  14. public:
  15. TBMemoryFile(void* _data, unsigned _size):
  16. data(_data),
  17. size(_size),
  18. currentPos(0)
  19. {
  20. }
  21. virtual ~TBMemoryFile()
  22. {
  23. if (data)
  24. free(data);
  25. }
  26. virtual long Size()
  27. {
  28. return (long) size;
  29. }
  30. virtual size_t Read(void *buf, size_t elemSize, size_t count)
  31. {
  32. size_t totalRead = elemSize * count;
  33. if (currentPos + totalRead > size)
  34. {
  35. if (currentPos >= size)
  36. return 0;
  37. totalRead = size - currentPos;
  38. }
  39. unsigned char* cdata = ((unsigned char*) data) + currentPos;
  40. memcpy(buf, cdata, totalRead);
  41. currentPos += totalRead;
  42. return totalRead;
  43. }
  44. private:
  45. void* data;
  46. size_t size;
  47. size_t currentPos;
  48. };
  49. // static
  50. TBFile *TBFile::Open(const char *filename, TBFileMode mode)
  51. {
  52. assert(reader_function);
  53. void* data = nullptr;
  54. unsigned size = 0;
  55. reader_function(filename, &data, &size);
  56. if (!data || !size)
  57. return nullptr;
  58. TBMemoryFile* tbmf = new TBMemoryFile(data, size);
  59. return tbmf;
  60. }
  61. }; // namespace tb
  62. #endif // TB_FILE_POSIX