ZipFile.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include "ZipFile.h"
  2. extern "C"
  3. {
  4. #include "miniz/miniz.h"
  5. }
  6. USING_NS_BF;
  7. class ZipFile::Data
  8. {
  9. public:
  10. bool mIsWriter;
  11. mz_zip_archive mZip;
  12. };
  13. ZipFile::ZipFile()
  14. {
  15. mData = NULL;
  16. }
  17. ZipFile::~ZipFile()
  18. {
  19. if (mData != NULL)
  20. Close();
  21. }
  22. bool ZipFile::Open(const StringImpl& filePath)
  23. {
  24. if (mData != NULL)
  25. Close();
  26. mData = new ZipFile::Data();
  27. memset(mData, 0, sizeof(ZipFile::Data));
  28. if (!mz_zip_reader_init_file(&mData->mZip, filePath.c_str(), 0))
  29. return false;
  30. return true;
  31. }
  32. bool ZipFile::Create(const StringImpl& filePath)
  33. {
  34. if (mData != NULL)
  35. Close();
  36. mData = new ZipFile::Data();
  37. memset(mData, 0, sizeof(ZipFile::Data));
  38. if (!mz_zip_writer_init_file(&mData->mZip, filePath.c_str(), 0))
  39. {
  40. delete mData;
  41. mData = NULL;
  42. return false;
  43. }
  44. mData->mIsWriter = true;
  45. return true;
  46. }
  47. bool ZipFile::Close()
  48. {
  49. if (mData == NULL)
  50. return false;
  51. if (mData->mIsWriter)
  52. {
  53. if (!mz_zip_writer_finalize_archive(&mData->mZip))
  54. return false;
  55. if (!mz_zip_writer_end(&mData->mZip))
  56. return false;
  57. }
  58. else
  59. {
  60. if (!mz_zip_reader_end(&mData->mZip))
  61. return false;
  62. }
  63. return true;
  64. }
  65. bool ZipFile::IsOpen()
  66. {
  67. return mData != NULL;
  68. }
  69. bool ZipFile::Add(const StringImpl& fileName, Span<uint8> data)
  70. {
  71. if (mData == NULL)
  72. return false;
  73. if (!mz_zip_writer_add_mem(&mData->mZip, fileName.c_str(), data.mVals, data.mSize, MZ_NO_COMPRESSION))
  74. return false;
  75. return true;
  76. }
  77. bool ZipFile::Get(const StringImpl& fileName, Array<uint8>& data)
  78. {
  79. if (mData == NULL)
  80. return false;
  81. int idx = mz_zip_reader_locate_file(&mData->mZip, fileName.c_str(), NULL, 0);
  82. if (idx < 0)
  83. return false;
  84. size_t size = 0;
  85. void* ptr = mz_zip_reader_extract_to_heap(&mData->mZip, idx, &size, 0);
  86. data.Insert(data.mSize, (uint8*)ptr, (intptr)size);
  87. return true;
  88. }