span_reader.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 <xtl/xspan.hpp>
  17. #include <cstring>
  18. namespace nncase
  19. {
  20. namespace runtime
  21. {
  22. class span_reader
  23. {
  24. public:
  25. span_reader(xtl::span<const uint8_t> span)
  26. : span_(span)
  27. {
  28. }
  29. bool empty() const noexcept { return span_.empty(); }
  30. template <class T>
  31. T read()
  32. {
  33. auto value = *reinterpret_cast<const T *>(span_.data());
  34. advance(sizeof(T));
  35. return value;
  36. }
  37. template <class T>
  38. T read_unaligned()
  39. {
  40. T value;
  41. std::memcpy(&value, span_.data(), sizeof(T));
  42. advance(sizeof(T));
  43. return value;
  44. }
  45. template <class T>
  46. void read(T &value)
  47. {
  48. value = *reinterpret_cast<const T *>(span_.data());
  49. advance(sizeof(T));
  50. }
  51. template <class T>
  52. void read_span(xtl::span<const T> &span, size_t size)
  53. {
  54. span = { reinterpret_cast<const T *>(span_.data()), size };
  55. advance(sizeof(T) * size);
  56. }
  57. template <class T, ptrdiff_t N>
  58. void read_span(xtl::span<const T, N> &span)
  59. {
  60. span = { reinterpret_cast<const T *>(span_.data()), N };
  61. advance(sizeof(T) * N);
  62. }
  63. void read_avail(xtl::span<const uint8_t> &span)
  64. {
  65. span = span_;
  66. span_ = {};
  67. }
  68. template <class T>
  69. const T *peek() const noexcept
  70. {
  71. return reinterpret_cast<const T *>(span_.data());
  72. }
  73. template <class T>
  74. void get_array(const T *&value, size_t size)
  75. {
  76. value = peek<T>();
  77. advance(size * sizeof(T));
  78. }
  79. template <class T>
  80. void get_ref(const T *&value)
  81. {
  82. value = peek<T>();
  83. advance(sizeof(T));
  84. }
  85. void skip(size_t count)
  86. {
  87. advance(count);
  88. }
  89. private:
  90. void advance(size_t count)
  91. {
  92. span_ = span_.subspan(count);
  93. }
  94. private:
  95. xtl::span<const uint8_t> span_;
  96. };
  97. }
  98. }