stream_flags_encoder.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // SPDX-License-Identifier: 0BSD
  2. ///////////////////////////////////////////////////////////////////////////////
  3. //
  4. /// \file stream_flags_encoder.c
  5. /// \brief Encodes Stream Header and Stream Footer for .xz files
  6. //
  7. // Author: Lasse Collin
  8. //
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #include "stream_flags_common.h"
  11. static bool
  12. stream_flags_encode(const lzma_stream_flags *options, uint8_t *out)
  13. {
  14. if ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)
  15. return true;
  16. out[0] = 0x00;
  17. out[1] = options->check;
  18. return false;
  19. }
  20. extern LZMA_API(lzma_ret)
  21. lzma_stream_header_encode(const lzma_stream_flags *options, uint8_t *out)
  22. {
  23. assert(sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE
  24. + 4 == LZMA_STREAM_HEADER_SIZE);
  25. if (options->version != 0)
  26. return LZMA_OPTIONS_ERROR;
  27. // Magic
  28. memcpy(out, lzma_header_magic, sizeof(lzma_header_magic));
  29. // Stream Flags
  30. if (stream_flags_encode(options, out + sizeof(lzma_header_magic)))
  31. return LZMA_PROG_ERROR;
  32. // CRC32 of the Stream Header
  33. const uint32_t crc = lzma_crc32(out + sizeof(lzma_header_magic),
  34. LZMA_STREAM_FLAGS_SIZE, 0);
  35. write32le(out + sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE,
  36. crc);
  37. return LZMA_OK;
  38. }
  39. extern LZMA_API(lzma_ret)
  40. lzma_stream_footer_encode(const lzma_stream_flags *options, uint8_t *out)
  41. {
  42. assert(2 * 4 + LZMA_STREAM_FLAGS_SIZE + sizeof(lzma_footer_magic)
  43. == LZMA_STREAM_HEADER_SIZE);
  44. if (options->version != 0)
  45. return LZMA_OPTIONS_ERROR;
  46. // Backward Size
  47. if (!is_backward_size_valid(options))
  48. return LZMA_PROG_ERROR;
  49. write32le(out + 4, options->backward_size / 4 - 1);
  50. // Stream Flags
  51. if (stream_flags_encode(options, out + 2 * 4))
  52. return LZMA_PROG_ERROR;
  53. // CRC32
  54. const uint32_t crc = lzma_crc32(
  55. out + 4, 4 + LZMA_STREAM_FLAGS_SIZE, 0);
  56. write32le(out, crc);
  57. // Magic
  58. memcpy(out + 2 * 4 + LZMA_STREAM_FLAGS_SIZE,
  59. lzma_footer_magic, sizeof(lzma_footer_magic));
  60. return LZMA_OK;
  61. }