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.

82 lines
2.2 KiB

2 months ago
  1. #include <cstdio>
  2. #include <sparsepp/spp.h>
  3. using spp::sparse_hash_map;
  4. using namespace std;
  5. class FileSerializer
  6. {
  7. public:
  8. // serialize basic types to FILE
  9. // -----------------------------
  10. template <class T>
  11. bool operator()(FILE *fp, const T& value)
  12. {
  13. return fwrite((const void *)&value, sizeof(value), 1, fp) == 1;
  14. }
  15. template <class T>
  16. bool operator()(FILE *fp, T* value)
  17. {
  18. return fread((void *)value, sizeof(*value), 1, fp) == 1;
  19. }
  20. // serialize std::string to FILE
  21. // -----------------------------
  22. bool operator()(FILE *fp, const string& value)
  23. {
  24. const size_t size = value.size();
  25. return (*this)(fp, size) && fwrite(value.c_str(), size, 1, fp) == 1;
  26. }
  27. bool operator()(FILE *fp, string* value)
  28. {
  29. size_t size;
  30. if (!(*this)(fp, &size))
  31. return false;
  32. char* buf = new char[size];
  33. if (fread(buf, size, 1, fp) != 1)
  34. {
  35. delete [] buf;
  36. return false;
  37. }
  38. new (value) string(buf, (size_t)size);
  39. delete[] buf;
  40. return true;
  41. }
  42. // serialize std::pair<const A, B> to FILE - needed for maps
  43. // ---------------------------------------------------------
  44. template <class A, class B>
  45. bool operator()(FILE *fp, const std::pair<const A, B>& value)
  46. {
  47. return (*this)(fp, value.first) && (*this)(fp, value.second);
  48. }
  49. template <class A, class B>
  50. bool operator()(FILE *fp, std::pair<const A, B> *value)
  51. {
  52. return (*this)(fp, (A *)&value->first) && (*this)(fp, &value->second);
  53. }
  54. };
  55. int main(int, char* [])
  56. {
  57. sparse_hash_map<string, int> age{ { "John", 12 }, {"Jane", 13 }, { "Fred", 8 } };
  58. // serialize age hash_map to "ages.dmp" file
  59. FILE *out = fopen("ages.dmp", "wb");
  60. age.serialize(FileSerializer(), out);
  61. fclose(out);
  62. sparse_hash_map<string, int> age_read;
  63. // read from "ages.dmp" file into age_read hash_map
  64. FILE *input = fopen("ages.dmp", "rb");
  65. age_read.unserialize(FileSerializer(), input);
  66. fclose(input);
  67. // print out contents of age_read to verify correct serialization
  68. for (auto& v : age_read)
  69. printf("age_read: %s -> %d\n", v.first.c_str(), v.second);
  70. }