1207753Smm///////////////////////////////////////////////////////////////////////////////
2207753Smm//
3207753Smm/// \file       delta_common.c
4207753Smm/// \brief      Common stuff for Delta encoder and decoder
5207753Smm//
6207753Smm//  Author:     Lasse Collin
7207753Smm//
8207753Smm//  This file has been put into the public domain.
9207753Smm//  You can do whatever you want with this file.
10207753Smm//
11207753Smm///////////////////////////////////////////////////////////////////////////////
12207753Smm
13207753Smm#include "delta_common.h"
14207753Smm#include "delta_private.h"
15207753Smm
16207753Smm
17207753Smmstatic void
18292588Sdelphijdelta_coder_end(lzma_coder *coder, const lzma_allocator *allocator)
19207753Smm{
20207753Smm	lzma_next_end(&coder->next, allocator);
21207753Smm	lzma_free(coder, allocator);
22207753Smm	return;
23207753Smm}
24207753Smm
25207753Smm
26207753Smmextern lzma_ret
27292588Sdelphijlzma_delta_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,
28207753Smm		const lzma_filter_info *filters)
29207753Smm{
30207753Smm	// Allocate memory for the decoder if needed.
31207753Smm	if (next->coder == NULL) {
32207753Smm		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
33207753Smm		if (next->coder == NULL)
34207753Smm			return LZMA_MEM_ERROR;
35207753Smm
36207753Smm		// End function is the same for encoder and decoder.
37207753Smm		next->end = &delta_coder_end;
38207753Smm		next->coder->next = LZMA_NEXT_CODER_INIT;
39207753Smm	}
40207753Smm
41207753Smm	// Validate the options.
42207753Smm	if (lzma_delta_coder_memusage(filters[0].options) == UINT64_MAX)
43207753Smm		return LZMA_OPTIONS_ERROR;
44207753Smm
45207753Smm	// Set the delta distance.
46207753Smm	const lzma_options_delta *opt = filters[0].options;
47207753Smm	next->coder->distance = opt->dist;
48207753Smm
49207753Smm	// Initialize the rest of the variables.
50207753Smm	next->coder->pos = 0;
51207753Smm	memzero(next->coder->history, LZMA_DELTA_DIST_MAX);
52207753Smm
53207753Smm	// Initialize the next decoder in the chain, if any.
54207753Smm	return lzma_next_filter_init(&next->coder->next,
55207753Smm			allocator, filters + 1);
56207753Smm}
57207753Smm
58207753Smm
59207753Smmextern uint64_t
60207753Smmlzma_delta_coder_memusage(const void *options)
61207753Smm{
62207753Smm	const lzma_options_delta *opt = options;
63207753Smm
64207753Smm	if (opt == NULL || opt->type != LZMA_DELTA_TYPE_BYTE
65207753Smm			|| opt->dist < LZMA_DELTA_DIST_MIN
66207753Smm			|| opt->dist > LZMA_DELTA_DIST_MAX)
67207753Smm		return UINT64_MAX;
68207753Smm
69207753Smm	return sizeof(lzma_coder);
70207753Smm}
71