virtual_file.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. XCC Utilities and Library
  3. Copyright (C) 2000 Olaf van der Spek <[email protected]>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "stdafx.h"
  16. #include "virtual_file.h"
  17. #include "file32.h"
  18. Cvirtual_file::Cvirtual_file()
  19. {
  20. }
  21. Cvirtual_file::Cvirtual_file(const Cvirtual_binary& d)
  22. {
  23. write(d);
  24. }
  25. void Cvirtual_file::clear()
  26. {
  27. m_data.clear();
  28. }
  29. void Cvirtual_file::compact()
  30. {
  31. if (m_data.size() == 1)
  32. return;
  33. Cvirtual_binary t = read();
  34. clear();
  35. write(t);
  36. }
  37. const byte* Cvirtual_file::data() const
  38. {
  39. if (m_data.size() != 1)
  40. return NULL;
  41. return m_data.begin()->data();
  42. }
  43. int Cvirtual_file::size() const
  44. {
  45. int r = 0;
  46. for (auto& i : m_data)
  47. r += i.size();
  48. return r;
  49. }
  50. int Cvirtual_file::save(const string& fname) const
  51. {
  52. Cfile32 f;
  53. int error = f.open_write(fname);
  54. if (!error)
  55. {
  56. for (auto& i : m_data)
  57. error = f.write(i);
  58. }
  59. return error;
  60. }
  61. int Cvirtual_file::load(const string& fname)
  62. {
  63. clear();
  64. Cvirtual_binary t;
  65. int error = t.load(fname);
  66. if (!error)
  67. write(t);
  68. return error;
  69. }
  70. Cvirtual_binary Cvirtual_file::read() const
  71. {
  72. if (m_data.size() == 1)
  73. return *m_data.begin();
  74. Cvirtual_binary r;
  75. read(r.write_start(size()));
  76. return r;
  77. }
  78. int Cvirtual_file::read(void* d) const
  79. {
  80. byte* w = reinterpret_cast<byte*>(d);
  81. for (auto& i : m_data)
  82. w += i.read(w);
  83. return w - reinterpret_cast<byte*>(d);
  84. }
  85. void Cvirtual_file::write(const Cvirtual_binary& d)
  86. {
  87. m_data.push_back(d);
  88. }
  89. void Cvirtual_file::write(const void* d, int cb_d)
  90. {
  91. write(Cvirtual_binary(d, cb_d));
  92. }