stream_codec.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /**
  2. * Copyright (C) 2015 Topology LP
  3. * Copyright (C) 2018 Jakob Petsovits
  4. * All rights reserved.
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to
  8. * deal in the Software without restriction, including without limitation the
  9. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. * sell copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. * IN THE SOFTWARE.
  23. */
  24. #ifndef CPPCODEC_DETAIL_STREAM_CODEC
  25. #define CPPCODEC_DETAIL_STREAM_CODEC
  26. #include <limits>
  27. #include <stdlib.h> // for abort()
  28. #include <stdint.h>
  29. #include "../parse_error.hpp"
  30. #include "config.hpp"
  31. namespace cppcodec {
  32. namespace detail {
  33. using alphabet_index_t = uint_fast16_t;
  34. template <typename Codec, typename CodecVariant>
  35. class stream_codec
  36. {
  37. public:
  38. template <typename Result, typename ResultState> static void encode(
  39. Result& encoded_result, ResultState&, const uint8_t* binary, size_t binary_size);
  40. template <typename Result, typename ResultState> static void decode(
  41. Result& binary_result, ResultState&, const char* encoded, size_t encoded_size);
  42. static constexpr size_t encoded_size(size_t binary_size) noexcept;
  43. static constexpr size_t decoded_max_size(size_t encoded_size) noexcept;
  44. };
  45. template <bool GeneratesPadding> // default for CodecVariant::generates_padding() == false
  46. struct padder {
  47. template <typename CodecVariant, typename Result, typename ResultState, typename EncodedBlockSizeT>
  48. CPPCODEC_ALWAYS_INLINE void operator()(Result&, ResultState&, EncodedBlockSizeT) { }
  49. };
  50. template<> // specialization for CodecVariant::generates_padding() == true
  51. struct padder<true> {
  52. template <typename CodecVariant, typename Result, typename ResultState, typename EncodedBlockSizeT>
  53. CPPCODEC_ALWAYS_INLINE void operator()(
  54. Result& encoded, ResultState& state, EncodedBlockSizeT num_padding_characters)
  55. {
  56. for (EncodedBlockSizeT i = 0; i < num_padding_characters; ++i) {
  57. data::put(encoded, state, CodecVariant::padding_symbol());
  58. }
  59. }
  60. };
  61. template <size_t I>
  62. struct enc {
  63. // Block encoding: Go from 0 to (block size - 1), append a symbol for each iteration unconditionally.
  64. template <typename Codec, typename CodecVariant, typename Result, typename ResultState>
  65. static CPPCODEC_ALWAYS_INLINE void block(Result& encoded, ResultState& state, const uint8_t* src)
  66. {
  67. using EncodedBlockSizeT = decltype(Codec::encoded_block_size());
  68. constexpr static const EncodedBlockSizeT SymbolIndex = static_cast<EncodedBlockSizeT>(I - 1);
  69. enc<I - 1>().template block<Codec, CodecVariant>(encoded, state, src);
  70. data::put(encoded, state, CodecVariant::symbol(Codec::template index<SymbolIndex>(src)));
  71. }
  72. // Tail encoding: Go from 0 until (runtime) num_symbols, append a symbol for each iteration.
  73. template <typename Codec, typename CodecVariant, typename Result, typename ResultState,
  74. typename EncodedBlockSizeT = decltype(Codec::encoded_block_size())>
  75. static CPPCODEC_ALWAYS_INLINE void tail(
  76. Result& encoded, ResultState& state, const uint8_t* src, EncodedBlockSizeT num_symbols)
  77. {
  78. constexpr static const EncodedBlockSizeT SymbolIndex = Codec::encoded_block_size() - I;
  79. constexpr static const EncodedBlockSizeT NumSymbols = SymbolIndex + static_cast<EncodedBlockSizeT>(1);
  80. if (num_symbols == NumSymbols) {
  81. data::put(encoded, state, CodecVariant::symbol(Codec::template index_last<SymbolIndex>(src)));
  82. padder<CodecVariant::generates_padding()> pad;
  83. #ifdef _MSC_VER
  84. pad.operator()<CodecVariant>(encoded, state, Codec::encoded_block_size() - NumSymbols);
  85. #else
  86. pad.template operator()<CodecVariant>(encoded, state, Codec::encoded_block_size() - NumSymbols);
  87. #endif
  88. return;
  89. }
  90. data::put(encoded, state, CodecVariant::symbol(Codec::template index<SymbolIndex>(src)));
  91. enc<I - 1>().template tail<Codec, CodecVariant>(encoded, state, src, num_symbols);
  92. }
  93. };
  94. template<> // terminating specialization
  95. struct enc<0> {
  96. template <typename Codec, typename CodecVariant, typename Result, typename ResultState>
  97. static CPPCODEC_ALWAYS_INLINE void block(Result&, ResultState&, const uint8_t*) { }
  98. template <typename Codec, typename CodecVariant, typename Result, typename ResultState,
  99. typename EncodedBlockSizeT = decltype(Codec::encoded_block_size())>
  100. static CPPCODEC_ALWAYS_INLINE void tail(Result&, ResultState&, const uint8_t*, EncodedBlockSizeT)
  101. {
  102. abort(); // Not reached: block() should be called if num_symbols == block size, not tail().
  103. }
  104. };
  105. template <typename Codec, typename CodecVariant>
  106. template <typename Result, typename ResultState>
  107. inline void stream_codec<Codec, CodecVariant>::encode(
  108. Result& encoded_result, ResultState& state,
  109. const uint8_t* src, size_t src_size)
  110. {
  111. using encoder = enc<Codec::encoded_block_size()>;
  112. const uint8_t* src_end = src + src_size;
  113. if (src_size >= Codec::binary_block_size()) {
  114. src_end -= Codec::binary_block_size();
  115. for (; src <= src_end; src += Codec::binary_block_size()) {
  116. encoder::template block<Codec, CodecVariant>(encoded_result, state, src);
  117. }
  118. src_end += Codec::binary_block_size();
  119. }
  120. if (src_end > src) {
  121. auto remaining_src_len = src_end - src;
  122. if (!remaining_src_len || remaining_src_len >= Codec::binary_block_size()) {
  123. abort();
  124. return;
  125. }
  126. auto num_symbols = Codec::num_encoded_tail_symbols(static_cast<uint8_t>(remaining_src_len));
  127. encoder::template tail<Codec, CodecVariant>(encoded_result, state, src, num_symbols);
  128. }
  129. }
  130. // Range & lookup table generation, see
  131. // http://stackoverflow.com/questions/13313980/populate-an-array-using-constexpr-at-compile-time
  132. // and http://cplusadd.blogspot.ca/2013/02/c11-compile-time-lookup-tablearray-with.html
  133. template<unsigned... Is> struct seq {};
  134. template<unsigned N, unsigned... Is>
  135. struct gen_seq : gen_seq<N - 4, N - 4, N - 3, N - 2, N - 1, Is...> {
  136. // Clang up to 3.6 has a limit of 256 for template recursion,
  137. // so pass a few more symbols at once to make it work.
  138. static_assert(N % 4 == 0, "I must be divisible by 4 to eventually end at 0");
  139. };
  140. template<unsigned... Is>
  141. struct gen_seq<0, Is...> : seq<Is...> {};
  142. template <size_t N>
  143. struct lookup_table_t {
  144. alphabet_index_t lookup[N];
  145. static constexpr size_t size = N;
  146. };
  147. template<typename LambdaType, unsigned... Is>
  148. constexpr lookup_table_t<sizeof...(Is)> make_lookup_table(seq<Is...>, LambdaType value_for_index) {
  149. return { { value_for_index(Is)... } };
  150. }
  151. template<unsigned N, typename LambdaType>
  152. constexpr lookup_table_t<N> make_lookup_table(LambdaType evalFunc) {
  153. return make_lookup_table(gen_seq<N>(), evalFunc);
  154. }
  155. // CodecVariant::symbol() provides a symbol for an index.
  156. // Use recursive templates to get the inverse lookup table for fast decoding.
  157. template <typename T>
  158. static CPPCODEC_ALWAYS_INLINE constexpr size_t num_possible_values()
  159. {
  160. return static_cast<size_t>(
  161. static_cast<intmax_t>(std::numeric_limits<T>::max())
  162. - static_cast<intmax_t>(std::numeric_limits<T>::min()) + 1);
  163. }
  164. template <typename CodecVariant, alphabet_index_t InvalidIdx, size_t I>
  165. struct index_if_in_alphabet {
  166. static CPPCODEC_ALWAYS_INLINE constexpr alphabet_index_t for_symbol(char symbol)
  167. {
  168. return (CodecVariant::symbol(
  169. static_cast<alphabet_index_t>(CodecVariant::alphabet_size() - I)) == symbol)
  170. ? static_cast<alphabet_index_t>(CodecVariant::alphabet_size() - I)
  171. : index_if_in_alphabet<CodecVariant, InvalidIdx, I - 1>::for_symbol(symbol);
  172. }
  173. };
  174. template <typename CodecVariant, alphabet_index_t InvalidIdx>
  175. struct index_if_in_alphabet<CodecVariant, InvalidIdx, 0> { // terminating specialization
  176. static CPPCODEC_ALWAYS_INLINE constexpr alphabet_index_t for_symbol(char)
  177. {
  178. return InvalidIdx;
  179. }
  180. };
  181. template <typename CodecVariant, size_t I>
  182. struct padding_searcher {
  183. static CPPCODEC_ALWAYS_INLINE constexpr bool exists_padding_symbol()
  184. {
  185. // Clang up to 3.6 has a limit of 256 for template recursion,
  186. // so pass a few more symbols at once to make it work.
  187. static_assert(I % 4 == 0, "I must be divisible by 4 to eventually end at 0");
  188. return CodecVariant::is_padding_symbol(
  189. static_cast<char>(num_possible_values<char>() - I - 4))
  190. || CodecVariant::is_padding_symbol(
  191. static_cast<char>(num_possible_values<char>() - I - 3))
  192. || CodecVariant::is_padding_symbol(
  193. static_cast<char>(num_possible_values<char>() - I - 2))
  194. || CodecVariant::is_padding_symbol(
  195. static_cast<char>(num_possible_values<char>() - I - 1))
  196. || padding_searcher<CodecVariant, I - 4>::exists_padding_symbol();
  197. }
  198. };
  199. template <typename CodecVariant>
  200. struct padding_searcher<CodecVariant, 0> { // terminating specialization
  201. static CPPCODEC_ALWAYS_INLINE constexpr bool exists_padding_symbol() { return false; }
  202. };
  203. template <typename CodecVariant>
  204. struct alphabet_index_info
  205. {
  206. static constexpr const size_t num_possible_symbols = num_possible_values<char>();
  207. static constexpr const alphabet_index_t padding_idx = 1 << 8;
  208. static constexpr const alphabet_index_t invalid_idx = 1 << 9;
  209. static constexpr const alphabet_index_t eof_idx = 1 << 10;
  210. static constexpr const alphabet_index_t stop_character_mask = static_cast<alphabet_index_t>(~0xFFu);
  211. static constexpr const bool padding_allowed = padding_searcher<
  212. CodecVariant, num_possible_symbols>::exists_padding_symbol();
  213. static CPPCODEC_ALWAYS_INLINE constexpr bool allows_padding()
  214. {
  215. return padding_allowed;
  216. }
  217. static CPPCODEC_ALWAYS_INLINE constexpr bool is_padding(alphabet_index_t idx)
  218. {
  219. return allows_padding() ? (idx == padding_idx) : false;
  220. }
  221. static CPPCODEC_ALWAYS_INLINE constexpr bool is_invalid(alphabet_index_t idx) { return idx == invalid_idx; }
  222. static CPPCODEC_ALWAYS_INLINE constexpr bool is_eof(alphabet_index_t idx) { return idx == eof_idx; }
  223. static CPPCODEC_ALWAYS_INLINE constexpr bool is_stop_character(alphabet_index_t idx)
  224. {
  225. return (idx & stop_character_mask) != 0;
  226. }
  227. private:
  228. static CPPCODEC_ALWAYS_INLINE constexpr
  229. alphabet_index_t valid_index_or(alphabet_index_t a, alphabet_index_t b)
  230. {
  231. return a == invalid_idx ? b : a;
  232. }
  233. using idx_if_in_alphabet = index_if_in_alphabet<
  234. CodecVariant, invalid_idx, CodecVariant::alphabet_size()>;
  235. static CPPCODEC_ALWAYS_INLINE constexpr alphabet_index_t index_of(char symbol)
  236. {
  237. return valid_index_or(idx_if_in_alphabet::for_symbol(symbol),
  238. CodecVariant::is_eof_symbol(symbol) ? eof_idx
  239. : CodecVariant::is_padding_symbol(symbol) ? padding_idx
  240. : invalid_idx);
  241. }
  242. // GCC <= 4.9 has a bug with retaining constexpr when passing a function pointer.
  243. // To get around this, we'll create a callable with operator() and pass that one.
  244. // Unfortunately, MSVC prior to VS 2017 (for MinSizeRel or Release builds)
  245. // chokes on this by compiling the project in 20 minutes instead of seconds.
  246. // So let's define two separate variants and remove the old GCC one whenever we
  247. // decide not to support GCC < 5.0 anymore.
  248. #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
  249. struct index_at {
  250. CPPCODEC_ALWAYS_INLINE constexpr alphabet_index_t operator()(size_t symbol) const {
  251. return index_of(CodecVariant::normalized_symbol(static_cast<char>(symbol)));
  252. }
  253. };
  254. #else
  255. static CPPCODEC_ALWAYS_INLINE constexpr alphabet_index_t index_at(size_t symbol)
  256. {
  257. return index_of(CodecVariant::normalized_symbol(static_cast<char>(symbol)));
  258. }
  259. #endif
  260. public:
  261. struct lookup {
  262. static CPPCODEC_ALWAYS_INLINE alphabet_index_t for_symbol(char symbol)
  263. {
  264. #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
  265. static constexpr const auto t = make_lookup_table<num_possible_symbols>(index_at());
  266. #else
  267. static constexpr const auto t = make_lookup_table<num_possible_symbols>(&index_at);
  268. #endif
  269. static_assert(t.size == num_possible_symbols,
  270. "lookup table must cover each possible (character) symbol");
  271. return t.lookup[static_cast<uint8_t>(symbol)];
  272. }
  273. };
  274. };
  275. //
  276. // At long last! The actual decode/encode functions.
  277. template <typename Codec, typename CodecVariant>
  278. template <typename Result, typename ResultState>
  279. inline void stream_codec<Codec, CodecVariant>::decode(
  280. Result& binary_result, ResultState& state,
  281. const char* src_encoded, size_t src_size)
  282. {
  283. using alphabet_index_lookup = typename alphabet_index_info<CodecVariant>::lookup;
  284. const char* src = src_encoded;
  285. const char* src_end = src + src_size;
  286. alphabet_index_t alphabet_indexes[Codec::encoded_block_size()] = {};
  287. alphabet_indexes[0] = alphabet_index_info<CodecVariant>::eof_idx;
  288. alphabet_index_t* const alphabet_index_start = &alphabet_indexes[0];
  289. alphabet_index_t* const alphabet_index_end = &alphabet_indexes[Codec::encoded_block_size()];
  290. alphabet_index_t* alphabet_index_ptr = &alphabet_indexes[0];
  291. while (src < src_end) {
  292. if (CodecVariant::should_ignore(*src)) {
  293. ++src;
  294. continue;
  295. }
  296. *alphabet_index_ptr = alphabet_index_lookup::for_symbol(*src);
  297. if (alphabet_index_info<CodecVariant>::is_stop_character(*alphabet_index_ptr)) {
  298. break;
  299. }
  300. ++src;
  301. ++alphabet_index_ptr;
  302. if (alphabet_index_ptr == alphabet_index_end) {
  303. Codec::decode_block(binary_result, state, alphabet_indexes);
  304. alphabet_index_ptr = alphabet_index_start;
  305. }
  306. }
  307. if (alphabet_index_info<CodecVariant>::is_invalid(*alphabet_index_ptr)) {
  308. throw symbol_error(*src);
  309. }
  310. ++src;
  311. alphabet_index_t* last_index_ptr = alphabet_index_ptr;
  312. if (alphabet_index_info<CodecVariant>::is_padding(*last_index_ptr)) {
  313. if (last_index_ptr == alphabet_index_start) {
  314. // Don't accept padding at the start of a block.
  315. // The encoder should have omitted that padding altogether.
  316. throw padding_error();
  317. }
  318. // We're in here because we just read a (first) padding character. Try to read more.
  319. // Count with last_index_ptr, but store in alphabet_index_ptr so we don't
  320. // overflow the array in case the input data is too long.
  321. ++last_index_ptr;
  322. while (src < src_end) {
  323. *alphabet_index_ptr = alphabet_index_lookup::for_symbol(*(src++));
  324. if (alphabet_index_info<CodecVariant>::is_eof(*alphabet_index_ptr)) {
  325. *alphabet_index_ptr = alphabet_index_info<CodecVariant>::padding_idx;
  326. break;
  327. }
  328. if (!alphabet_index_info<CodecVariant>::is_padding(*alphabet_index_ptr)) {
  329. throw padding_error();
  330. }
  331. ++last_index_ptr;
  332. if (last_index_ptr > alphabet_index_end) {
  333. throw padding_error();
  334. }
  335. }
  336. }
  337. if (last_index_ptr != alphabet_index_start) {
  338. if ((CodecVariant::requires_padding()
  339. || alphabet_index_info<CodecVariant>::is_padding(*alphabet_index_ptr)
  340. ) && last_index_ptr != alphabet_index_end)
  341. {
  342. // If the input is not a multiple of the block size then the input is incorrect.
  343. throw padding_error();
  344. }
  345. if (alphabet_index_ptr >= alphabet_index_end) {
  346. abort();
  347. return;
  348. }
  349. Codec::decode_tail(binary_result, state, alphabet_indexes,
  350. static_cast<size_t>(alphabet_index_ptr - alphabet_index_start));
  351. }
  352. }
  353. template <typename Codec, typename CodecVariant>
  354. inline constexpr size_t stream_codec<Codec, CodecVariant>::encoded_size(size_t binary_size) noexcept
  355. {
  356. using C = Codec;
  357. // constexpr rules make this a lot harder to read than it actually is.
  358. return CodecVariant::generates_padding()
  359. // With padding, the encoded size is a multiple of the encoded block size.
  360. // To calculate that, round the binary size up to multiple of the binary block size,
  361. // then convert to encoded by multiplying with { base32: 8/5, base64: 4/3 }.
  362. ? (binary_size + (C::binary_block_size() - 1)
  363. - ((binary_size + (C::binary_block_size() - 1)) % C::binary_block_size()))
  364. * C::encoded_block_size() / C::binary_block_size()
  365. // No padding: only pad to the next multiple of 5 bits, i.e. at most a single extra byte.
  366. : (binary_size * C::encoded_block_size() / C::binary_block_size())
  367. + (((binary_size * C::encoded_block_size()) % C::binary_block_size()) ? 1 : 0);
  368. }
  369. template <typename Codec, typename CodecVariant>
  370. inline constexpr size_t stream_codec<Codec, CodecVariant>::decoded_max_size(size_t encoded_size) noexcept
  371. {
  372. using C = Codec;
  373. return CodecVariant::requires_padding()
  374. ? (encoded_size / C::encoded_block_size() * C::binary_block_size())
  375. : (encoded_size / C::encoded_block_size() * C::binary_block_size())
  376. + ((encoded_size % C::encoded_block_size())
  377. * C::binary_block_size() / C::encoded_block_size());
  378. }
  379. } // namespace detail
  380. } // namespace cppcodec
  381. #endif // CPPCODEC_DETAIL_STREAM_CODEC