aboutsummaryrefslogtreecommitdiff
path: root/src/liblzma/common/stream_flags_encoder.c
blob: 4efbb6f4dfecd284119d2e5d41d690c70ee204b8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
///////////////////////////////////////////////////////////////////////////////
//
/// \file       stream_flags_encoder.c
/// \brief      Encodes Stream Header and Stream Footer for .lzma files
//
//  Copyright (C) 2007 Lasse Collin
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
///////////////////////////////////////////////////////////////////////////////

#include "stream_common.h"


static bool
stream_flags_encode(const lzma_stream_flags *options, uint8_t *out)
{
	if ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)
		return true;

	out[0] = 0x00;
	out[1] = options->check;

	return false;
}


extern LZMA_API lzma_ret
lzma_stream_header_encode(const lzma_stream_flags *options, uint8_t *out)
{
	assert(sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE
			+ 4 == LZMA_STREAM_HEADER_SIZE);

	// Magic
	memcpy(out, lzma_header_magic, sizeof(lzma_header_magic));

	// Stream Flags
	if (stream_flags_encode(options, out + sizeof(lzma_header_magic)))
		return LZMA_PROG_ERROR;

	// CRC32 of the Stream Header
	const uint32_t crc = lzma_crc32(out + sizeof(lzma_header_magic),
			LZMA_STREAM_FLAGS_SIZE, 0);

	integer_write_32(out + sizeof(lzma_header_magic)
			+ LZMA_STREAM_FLAGS_SIZE, crc);

	return LZMA_OK;
}


extern LZMA_API lzma_ret
lzma_stream_footer_encode(const lzma_stream_flags *options, uint8_t *out)
{
	assert(2 * 4 + LZMA_STREAM_FLAGS_SIZE + sizeof(lzma_footer_magic)
			== LZMA_STREAM_HEADER_SIZE);

	// Backward Size
	if (options->backward_size < LZMA_BACKWARD_SIZE_MIN
			|| options->backward_size > LZMA_BACKWARD_SIZE_MAX
			|| (options->backward_size & 3))
		return LZMA_PROG_ERROR;

	integer_write_32(out + 4, options->backward_size / 4 - 1);

	// Stream Flags
	if (stream_flags_encode(options, out + 2 * 4))
		return LZMA_PROG_ERROR;

	// CRC32
	const uint32_t crc = lzma_crc32(
			out + 4, 4 + LZMA_STREAM_FLAGS_SIZE, 0);

	integer_write_32(out, crc);

	// Magic
	memcpy(out + 2 * 4 + LZMA_STREAM_FLAGS_SIZE,
			lzma_footer_magic, sizeof(lzma_footer_magic));

	return LZMA_OK;
}