binary_writer.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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_writer
  23. {
  24. public:
  25. binary_writer(std::ostream &stream)
  26. : stream_(stream)
  27. {
  28. }
  29. template <class T>
  30. void write(T &&value)
  31. {
  32. stream_.write(reinterpret_cast<const char *>(&value), sizeof(value));
  33. }
  34. template <class T>
  35. void write_array(xtl::span<const T> value)
  36. {
  37. stream_.write(reinterpret_cast<const char *>(value.data()), value.size_bytes());
  38. }
  39. std::streampos position() const
  40. {
  41. return stream_.tellp();
  42. }
  43. void position(std::streampos pos)
  44. {
  45. stream_.seekp(pos);
  46. }
  47. std::streamoff align_position(size_t alignment)
  48. {
  49. auto pos = position();
  50. auto rem = pos % alignment;
  51. if (rem != 0)
  52. {
  53. auto off = std::streamoff(alignment - rem);
  54. position(pos + off);
  55. return off;
  56. }
  57. return 0;
  58. }
  59. private:
  60. std::ostream &stream_;
  61. };
  62. }
  63. }