binary_reader.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Copyright 2019-2020 Canaan Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #pragma once
  16. #include <iostream>
  17. #include <xtl/xspan.hpp>
  18. namespace nncase
  19. {
  20. namespace runtime
  21. {
  22. class binary_reader
  23. {
  24. public:
  25. binary_reader(std::istream &stream)
  26. : stream_(stream)
  27. {
  28. }
  29. template <class T>
  30. T read()
  31. {
  32. T value;
  33. read(value);
  34. return value;
  35. }
  36. template <class T>
  37. void read(T &value)
  38. {
  39. stream_.read(reinterpret_cast<char *>(&value), sizeof(value));
  40. }
  41. template <class T>
  42. void read_array(xtl::span<T> value)
  43. {
  44. stream_.read(reinterpret_cast<char *>(value.data()), value.size_bytes());
  45. }
  46. std::streampos position() const
  47. {
  48. return stream_.tellg();
  49. }
  50. void position(std::streampos pos)
  51. {
  52. stream_.seekg(pos);
  53. }
  54. void skip(std::streamoff off)
  55. {
  56. stream_.seekg(off, std::ios::cur);
  57. }
  58. size_t avail()
  59. {
  60. auto pos = stream_.tellg();
  61. stream_.seekg(0, std::ios::end);
  62. auto end = stream_.tellg();
  63. stream_.seekg(pos);
  64. return size_t(end - pos);
  65. }
  66. private:
  67. std::istream &stream_;
  68. };
  69. }
  70. }