InputBitStream.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Concepts.h>
  9. #include <AK/Error.h>
  10. #include <AK/NonnullOwnPtr.h>
  11. #include <AK/NonnullRefPtr.h>
  12. #include <AK/OwnPtr.h>
  13. #include <AK/Span.h>
  14. #include <AK/StdLibExtraDetails.h>
  15. #include <AK/Types.h>
  16. #include <LibCore/Stream.h>
  17. namespace Core::Stream {
  18. /// A stream wrapper class that allows you to read arbitrary amounts of bits
  19. /// in big-endian order from another stream.
  20. /// Note that this stream does not own its underlying stream, it merely takes a reference.
  21. class BigEndianInputBitStream : public Stream {
  22. public:
  23. static ErrorOr<NonnullOwnPtr<BigEndianInputBitStream>> construct(Stream& stream)
  24. {
  25. return adopt_nonnull_own_or_enomem<BigEndianInputBitStream>(new BigEndianInputBitStream(stream));
  26. }
  27. // ^Stream
  28. virtual ErrorOr<Bytes> read(Bytes bytes) override
  29. {
  30. if (m_current_byte.has_value() && is_aligned_to_byte_boundary()) {
  31. bytes[0] = m_current_byte.release_value();
  32. return m_stream.read(bytes.slice(1));
  33. }
  34. align_to_byte_boundary();
  35. return m_stream.read(bytes);
  36. }
  37. virtual ErrorOr<size_t> write(ReadonlyBytes bytes) override { return m_stream.write(bytes); }
  38. virtual bool write_or_error(ReadonlyBytes bytes) override { return m_stream.write_or_error(bytes); }
  39. virtual bool is_eof() const override { return m_stream.is_eof() && !m_current_byte.has_value(); }
  40. virtual bool is_open() const override { return m_stream.is_open(); }
  41. virtual void close() override
  42. {
  43. m_stream.close();
  44. align_to_byte_boundary();
  45. }
  46. ErrorOr<bool> read_bit()
  47. {
  48. return read_bits<bool>(1);
  49. }
  50. /// Depending on the number of bits to read, the return type can be chosen appropriately.
  51. /// This avoids a bunch of static_cast<>'s for the user.
  52. // TODO: Support u128, u256 etc. as well: The concepts would be quite complex.
  53. template<Unsigned T = u64>
  54. ErrorOr<T> read_bits(size_t count)
  55. {
  56. if constexpr (IsSame<bool, T>) {
  57. VERIFY(count == 1);
  58. }
  59. T result = 0;
  60. size_t nread = 0;
  61. while (nread < count) {
  62. if (m_current_byte.has_value()) {
  63. if constexpr (!IsSame<bool, T> && !IsSame<u8, T>) {
  64. // read as many bytes as possible directly
  65. if (((count - nread) >= 8) && is_aligned_to_byte_boundary()) {
  66. // shift existing data over
  67. result <<= 8;
  68. result |= m_current_byte.value();
  69. nread += 8;
  70. m_current_byte.clear();
  71. } else {
  72. auto const bit = (m_current_byte.value() >> (7 - m_bit_offset)) & 1;
  73. result <<= 1;
  74. result |= bit;
  75. ++nread;
  76. if (m_bit_offset++ == 7)
  77. m_current_byte.clear();
  78. }
  79. } else {
  80. // Always take this branch for booleans or u8: there's no purpose in reading more than a single bit
  81. auto const bit = (m_current_byte.value() >> (7 - m_bit_offset)) & 1;
  82. if constexpr (IsSame<bool, T>)
  83. result = bit;
  84. else {
  85. result <<= 1;
  86. result |= bit;
  87. }
  88. ++nread;
  89. if (m_bit_offset++ == 7)
  90. m_current_byte.clear();
  91. }
  92. } else {
  93. auto temp_buffer = TRY(ByteBuffer::create_uninitialized(1));
  94. TRY(m_stream.read(temp_buffer.bytes()));
  95. m_current_byte = temp_buffer[0];
  96. m_bit_offset = 0;
  97. }
  98. }
  99. return result;
  100. }
  101. /// Discards any sub-byte stream positioning the input stream may be keeping track of.
  102. /// Non-bitwise reads will implicitly call this.
  103. void align_to_byte_boundary()
  104. {
  105. m_current_byte.clear();
  106. m_bit_offset = 0;
  107. }
  108. /// Whether we are (accidentally or intentionally) at a byte boundary right now.
  109. ALWAYS_INLINE bool is_aligned_to_byte_boundary() const { return m_bit_offset == 0; }
  110. private:
  111. BigEndianInputBitStream(Stream& stream)
  112. : m_stream(stream)
  113. {
  114. }
  115. Optional<u8> m_current_byte;
  116. size_t m_bit_offset { 0 };
  117. Stream& m_stream;
  118. };
  119. /// A stream wrapper class that allows you to read arbitrary amounts of bits
  120. /// in little-endian order from another stream.
  121. /// Note that this stream does not own its underlying stream, it merely takes a reference.
  122. class LittleEndianInputBitStream : public Stream {
  123. public:
  124. static ErrorOr<NonnullOwnPtr<LittleEndianInputBitStream>> construct(Stream& stream)
  125. {
  126. return adopt_nonnull_own_or_enomem<LittleEndianInputBitStream>(new LittleEndianInputBitStream(stream));
  127. }
  128. LittleEndianInputBitStream(Stream& stream)
  129. : m_stream(stream)
  130. {
  131. }
  132. // ^Stream
  133. virtual ErrorOr<Bytes> read(Bytes bytes) override
  134. {
  135. if (m_current_byte.has_value() && is_aligned_to_byte_boundary()) {
  136. bytes[0] = m_current_byte.release_value();
  137. return m_stream.read(bytes.slice(1));
  138. }
  139. align_to_byte_boundary();
  140. return m_stream.read(bytes);
  141. }
  142. virtual ErrorOr<size_t> write(ReadonlyBytes bytes) override { return m_stream.write(bytes); }
  143. virtual bool write_or_error(ReadonlyBytes bytes) override { return m_stream.write_or_error(bytes); }
  144. virtual bool is_eof() const override { return m_stream.is_eof() && !m_current_byte.has_value(); }
  145. virtual bool is_open() const override { return m_stream.is_open(); }
  146. virtual void close() override
  147. {
  148. m_stream.close();
  149. align_to_byte_boundary();
  150. }
  151. ErrorOr<bool> read_bit()
  152. {
  153. return read_bits<bool>(1);
  154. }
  155. /// Depending on the number of bits to read, the return type can be chosen appropriately.
  156. /// This avoids a bunch of static_cast<>'s for the user.
  157. // TODO: Support u128, u256 etc. as well: The concepts would be quite complex.
  158. template<Unsigned T = u64>
  159. ErrorOr<T> read_bits(size_t count)
  160. {
  161. if constexpr (IsSame<bool, T>) {
  162. VERIFY(count == 1);
  163. }
  164. T result = 0;
  165. size_t nread = 0;
  166. while (nread < count) {
  167. if (m_current_byte.has_value()) {
  168. if constexpr (!IsSame<bool, T> && !IsSame<u8, T>) {
  169. // read as many bytes as possible directly
  170. if (((count - nread) >= 8) && is_aligned_to_byte_boundary()) {
  171. // shift existing data over
  172. result |= (m_current_byte.value() << nread);
  173. nread += 8;
  174. m_current_byte.clear();
  175. } else {
  176. auto const bit = (m_current_byte.value() >> m_bit_offset) & 1;
  177. result |= (bit << nread);
  178. ++nread;
  179. if (m_bit_offset++ == 7)
  180. m_current_byte.clear();
  181. }
  182. } else {
  183. // Always take this branch for booleans or u8: there's no purpose in reading more than a single bit
  184. auto const bit = (m_current_byte.value() >> m_bit_offset) & 1;
  185. if constexpr (IsSame<bool, T>)
  186. result = bit;
  187. else
  188. result |= (bit << nread);
  189. ++nread;
  190. if (m_bit_offset++ == 7)
  191. m_current_byte.clear();
  192. }
  193. } else {
  194. auto temp_buffer = TRY(ByteBuffer::create_uninitialized(1));
  195. auto read_bytes = TRY(m_stream.read(temp_buffer.bytes()));
  196. if (read_bytes.is_empty())
  197. return Error::from_string_literal("eof");
  198. m_current_byte = temp_buffer[0];
  199. m_bit_offset = 0;
  200. }
  201. }
  202. return result;
  203. }
  204. /// Discards any sub-byte stream positioning the input stream may be keeping track of.
  205. /// Non-bitwise reads will implicitly call this.
  206. u8 align_to_byte_boundary()
  207. {
  208. u8 remaining_bits = m_current_byte.value_or(0) >> m_bit_offset;
  209. m_current_byte.clear();
  210. m_bit_offset = 0;
  211. return remaining_bits;
  212. }
  213. /// Whether we are (accidentally or intentionally) at a byte boundary right now.
  214. ALWAYS_INLINE bool is_aligned_to_byte_boundary() const { return m_bit_offset == 0; }
  215. private:
  216. Optional<u8> m_current_byte;
  217. size_t m_bit_offset { 0 };
  218. Stream& m_stream;
  219. };
  220. }