FileMemoryStream.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2020 Jérémie Dumas <[email protected]>
  4. // Copyright (C) 2021 Alec Jacobson <[email protected]>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public License
  7. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  8. // obtain one at http://mozilla.org/MPL/2.0/.
  9. #ifndef IGL_FILEMEMORYSTREAM_H
  10. #define IGL_FILEMEMORYSTREAM_H
  11. #include "igl_inline.h"
  12. #include <streambuf>
  13. #include <istream>
  14. #include <string>
  15. namespace igl {
  16. struct FileMemoryBuffer : public std::streambuf
  17. {
  18. char *p_start{nullptr};
  19. char *p_end{nullptr};
  20. size_t size;
  21. FileMemoryBuffer(char const *first_elem, size_t size)
  22. : p_start(const_cast<char *>(first_elem)), p_end(p_start + size),
  23. size(size)
  24. {
  25. setg(p_start, p_start, p_end);
  26. }
  27. pos_type seekoff(
  28. off_type off,
  29. std::ios_base::seekdir dir,
  30. std::ios_base::openmode which) override
  31. {
  32. if (dir == std::ios_base::cur)
  33. {
  34. gbump(static_cast<int>(off));
  35. }else
  36. {
  37. setg(p_start,(dir==std::ios_base::beg ? p_start : p_end) + off,p_end);
  38. }
  39. return gptr() - p_start;
  40. }
  41. pos_type seekpos(pos_type pos, std::ios_base::openmode which) override
  42. {
  43. return seekoff(pos, std::ios_base::beg, which);
  44. }
  45. };
  46. /// Class to convert a FILE * to an std::istream
  47. struct FileMemoryStream : virtual FileMemoryBuffer, public std::istream
  48. {
  49. FileMemoryStream( char const *first_elem, size_t size)
  50. : FileMemoryBuffer(first_elem, size),
  51. std::istream( static_cast<std::streambuf *>(this))
  52. {}
  53. };
  54. }
  55. #endif