stream_flags_encoder.c revision 207842
1178476Sjb///////////////////////////////////////////////////////////////////////////////
2178476Sjb//
3178476Sjb/// \file       stream_flags_encoder.c
4178476Sjb/// \brief      Encodes Stream Header and Stream Footer for .xz files
5178476Sjb//
6178476Sjb//  Author:     Lasse Collin
7178476Sjb//
8178476Sjb//  This file has been put into the public domain.
9178476Sjb//  You can do whatever you want with this file.
10178476Sjb//
11178476Sjb///////////////////////////////////////////////////////////////////////////////
12178476Sjb
13178476Sjb#include "stream_flags_common.h"
14178476Sjb
15178476Sjb
16178476Sjbstatic bool
17178476Sjbstream_flags_encode(const lzma_stream_flags *options, uint8_t *out)
18178476Sjb{
19178476Sjb	if ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)
20178476Sjb		return true;
21178476Sjb
22178476Sjb	out[0] = 0x00;
23178476Sjb	out[1] = options->check;
24178476Sjb
25178476Sjb	return false;
26178476Sjb}
27178476Sjb
28178476Sjb
29178476Sjbextern LZMA_API(lzma_ret)
30178476Sjblzma_stream_header_encode(const lzma_stream_flags *options, uint8_t *out)
31178476Sjb{
32178476Sjb	assert(sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE
33178476Sjb			+ 4 == LZMA_STREAM_HEADER_SIZE);
34178476Sjb
35178476Sjb	if (options->version != 0)
36178476Sjb		return LZMA_OPTIONS_ERROR;
37178476Sjb
38178476Sjb	// Magic
39178476Sjb	memcpy(out, lzma_header_magic, sizeof(lzma_header_magic));
40178476Sjb
41178476Sjb	// Stream Flags
42178476Sjb	if (stream_flags_encode(options, out + sizeof(lzma_header_magic)))
43178476Sjb		return LZMA_PROG_ERROR;
44178476Sjb
45178476Sjb	// CRC32 of the Stream Header
46178476Sjb	const uint32_t crc = lzma_crc32(out + sizeof(lzma_header_magic),
47178476Sjb			LZMA_STREAM_FLAGS_SIZE, 0);
48178476Sjb
49178476Sjb	unaligned_write32le(out + sizeof(lzma_header_magic)
50178476Sjb			+ LZMA_STREAM_FLAGS_SIZE, crc);
51178476Sjb
52178476Sjb	return LZMA_OK;
53178476Sjb}
54178476Sjb
55178476Sjb
56178476Sjbextern LZMA_API(lzma_ret)
57178476Sjblzma_stream_footer_encode(const lzma_stream_flags *options, uint8_t *out)
58{
59	assert(2 * 4 + LZMA_STREAM_FLAGS_SIZE + sizeof(lzma_footer_magic)
60			== LZMA_STREAM_HEADER_SIZE);
61
62	if (options->version != 0)
63		return LZMA_OPTIONS_ERROR;
64
65	// Backward Size
66	if (!is_backward_size_valid(options))
67		return LZMA_PROG_ERROR;
68
69	unaligned_write32le(out + 4, options->backward_size / 4 - 1);
70
71	// Stream Flags
72	if (stream_flags_encode(options, out + 2 * 4))
73		return LZMA_PROG_ERROR;
74
75	// CRC32
76	const uint32_t crc = lzma_crc32(
77			out + 4, 4 + LZMA_STREAM_FLAGS_SIZE, 0);
78
79	unaligned_write32le(out, crc);
80
81	// Magic
82	memcpy(out + 2 * 4 + LZMA_STREAM_FLAGS_SIZE,
83			lzma_footer_magic, sizeof(lzma_footer_magic));
84
85	return LZMA_OK;
86}
87