xref: /freebsd/contrib/xz/src/liblzma/delta/delta_common.c (revision 3416500aef140042c64bc149cb1ec6620483bc44)
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       delta_common.c
4 /// \brief      Common stuff for Delta encoder and decoder
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12 
13 #include "delta_common.h"
14 #include "delta_private.h"
15 
16 
17 static void
18 delta_coder_end(void *coder_ptr, const lzma_allocator *allocator)
19 {
20 	lzma_delta_coder *coder = coder_ptr;
21 	lzma_next_end(&coder->next, allocator);
22 	lzma_free(coder, allocator);
23 	return;
24 }
25 
26 
27 extern lzma_ret
28 lzma_delta_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,
29 		const lzma_filter_info *filters)
30 {
31 	// Allocate memory for the decoder if needed.
32 	lzma_delta_coder *coder = next->coder;
33 	if (coder == NULL) {
34 		coder = lzma_alloc(sizeof(lzma_delta_coder), allocator);
35 		if (coder == NULL)
36 			return LZMA_MEM_ERROR;
37 
38 		next->coder = coder;
39 
40 		// End function is the same for encoder and decoder.
41 		next->end = &delta_coder_end;
42 		coder->next = LZMA_NEXT_CODER_INIT;
43 	}
44 
45 	// Validate the options.
46 	if (lzma_delta_coder_memusage(filters[0].options) == UINT64_MAX)
47 		return LZMA_OPTIONS_ERROR;
48 
49 	// Set the delta distance.
50 	const lzma_options_delta *opt = filters[0].options;
51 	coder->distance = opt->dist;
52 
53 	// Initialize the rest of the variables.
54 	coder->pos = 0;
55 	memzero(coder->history, LZMA_DELTA_DIST_MAX);
56 
57 	// Initialize the next decoder in the chain, if any.
58 	return lzma_next_filter_init(&coder->next, allocator, filters + 1);
59 }
60 
61 
62 extern uint64_t
63 lzma_delta_coder_memusage(const void *options)
64 {
65 	const lzma_options_delta *opt = options;
66 
67 	if (opt == NULL || opt->type != LZMA_DELTA_TYPE_BYTE
68 			|| opt->dist < LZMA_DELTA_DIST_MIN
69 			|| opt->dist > LZMA_DELTA_DIST_MAX)
70 		return UINT64_MAX;
71 
72 	return sizeof(lzma_delta_coder);
73 }
74